home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / event-Xt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-30  |  76.6 KB  |  2,426 lines

  1. /* The event_stream interface for X11 with Xt, and/or tty frames.
  2.    Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.    Copyright (C) 1994, 1995 Amdahl Corporation.
  4.  
  5. This file is part of XEmacs.
  6.  
  7. XEmacs is free software; you can redistribute it and/or modify it
  8. under the terms of the GNU General Public License as published by the
  9. Free Software Foundation; either version 2, or (at your option) any
  10. later version.
  11.  
  12. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  13. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15. for more details.
  16.  
  17. You should have received a copy of the GNU General Public License
  18. along with XEmacs; see the file COPYING.  If not, write to the Free
  19. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. /* Synched up with: Not in FSF. */
  22.  
  23. #include <config.h>
  24. #include "lisp.h"
  25.  
  26. #include "device-x.h"
  27. #include "frame-x.h"
  28. #include "lwlib.h"
  29. #include "EmacsFrame.h"
  30.  
  31. #include "blocktype.h"
  32. #include "commands.h"
  33. #include "device-tty.h"
  34. #include "events.h"
  35. #include "process.h"
  36. #include "redisplay.h"
  37.  
  38. #include "systime.h"
  39. #include "sysproc.h" /* for MAXDESC */
  40.  
  41. #include "xintrinsicp.h"    /* CoreP.h needs this */
  42. #include <X11/CoreP.h>        /* Numerous places access the fields of
  43.                    a core widget directly.  We could
  44.                    use XtVaGetValues(), but ... */
  45.  
  46. static struct event_stream *Xt_event_stream;
  47.  
  48. /* With the new event model, all events go through XtDispatchEvent()
  49.    and are picked up by an event handler that is added to each frame
  50.    widget. (This is how it's supposed to be.) In the old method,
  51.    Emacs sucks out events directly from XtNextEvent() and only
  52.    dispatches the events that it doesn't need to deal with.  This
  53.    old way has lots of corresponding junk that is no longer
  54.    necessary: lwlib extensions, synthetic XAnyEvents, unnecessary
  55.    magic events, etc. */
  56.  
  57. /* The one and only one application context that Emacs uses. */
  58. XtAppContext Xt_app_con;
  59.  
  60. /* Do we accept events send by other clients? */
  61. int x_allow_sendevents;
  62.  
  63. int modifier_keys_are_sticky;
  64.  
  65. #ifdef DEBUG_XEMACS
  66. int x_debug_events;
  67. #endif
  68.  
  69. static int process_events_occurred;
  70. static int tty_events_occurred;
  71. static int fake_event_occurred;
  72.  
  73. /* Mask of bits indicating the tty descriptors that we wait for input on */
  74. static SELECT_TYPE tty_device_mask;
  75.  
  76. /* Mask of bits indicating the descriptors that we wait for input on */
  77. extern SELECT_TYPE input_wait_mask, process_only_mask, device_only_mask;
  78.  
  79. static String x_fallback_resources[] =
  80. {
  81.   /* This file is automatically generated from the app-defaults file
  82.      in ../etc/Emacs.ad.  These resources are consulted only if no
  83.      app-defaults file is found at all.
  84.    */
  85. # include "Emacs.ad.h"
  86.   0 };
  87.  
  88. void emacs_Xt_mapping_action (Widget w, XEvent *event);
  89. void debug_process_finalization (struct Lisp_Process *p);
  90. Lisp_Object dequeue_Xt_dispatch_event (void);
  91. void emacs_Xt_event_handler (Widget wid, XtPointer closure, XEvent *event,
  92.                  Boolean *continue_to_dispatch);
  93.  
  94. static int last_quit_check_signal_tick_count;
  95.  
  96. Lisp_Object Qkey_mapping;
  97.  
  98.  
  99. /************************************************************************/
  100. /*                            keymap handling                           */
  101. /************************************************************************/
  102.  
  103. /* X bogusly doesn't define the interpretations of any bits besides
  104.    ModControl, ModShift, and ModLock; so the Interclient Communication
  105.    Conventions Manual says that we have to bend over backwards to figure
  106.    out what the other modifier bits mean.  According to ICCCM:
  107.  
  108.    - Any keycode which is assigned ModControl is a "control" key.
  109.  
  110.    - Any modifier bit which is assigned to a keycode which generates Meta_L
  111.      or Meta_R is the modifier bit meaning "meta".  Likewise for Super, Hyper,
  112.      etc.
  113.  
  114.    - Any keypress event which contains ModControl in its state should be
  115.      interpreted as a "control" character.
  116.  
  117.    - Any keypress event which contains a modifier bit in its state which is
  118.      generated by a keycode whose corresponding keysym is Meta_L or Meta_R
  119.      should be interpreted as a "meta" character.  Likewise for Super, Hyper,
  120.      etc.
  121.  
  122.    - It is illegal for a keysym to be associated with more than one modifier
  123.      bit.
  124.  
  125.    This means that the only thing that emacs can reasonably interpret as a
  126.    "meta" key is a key whose keysym is Meta_L or Meta_R, and which generates
  127.    one of the modifier bits Mod1-Mod5.
  128.  
  129.    Unfortunately, many keyboards don't have Meta keys in their default
  130.    configuration.  So, if there are no Meta keys, but there are "Alt" keys,
  131.    emacs will interpret Alt as Meta.  If there are both Meta and Alt keys,
  132.    then the Meta keys mean "Meta", and the Alt keys mean "Alt" (it used to
  133.    mean "Symbol," but that just confused the hell out of way too many people).
  134.  
  135.    This works with the default configurations of the 19 keyboard-types I've
  136.    checked.
  137.  
  138.    Emacs detects keyboard configurations which violate the above rules, and
  139.    prints an error message on the standard-error-output.  (Perhaps it should
  140.    use a pop-up-window instead.)
  141.  */
  142.  
  143. static void
  144. x_reset_key_mapping (struct device *d)
  145. {
  146.   Display *display = DEVICE_X_DISPLAY (d);
  147.   struct x_device *xd = DEVICE_X_DATA (d);
  148.   int max_code;
  149.   if (xd->x_keysym_map)
  150.     XFree ((char *) xd->x_keysym_map);
  151.   XDisplayKeycodes (display, &xd->x_keysym_map_min_code,
  152.             &max_code);
  153.   xd->x_keysym_map =
  154.     XGetKeyboardMapping (display, xd->x_keysym_map_min_code,
  155.              max_code - xd->x_keysym_map_min_code + 1,
  156.              &xd->x_keysym_map_keysyms_per_code);
  157. }
  158.  
  159. static CONST char *
  160. index_to_name (int indice)
  161. {
  162.   return ((indice == ShiftMapIndex ? "ModShift"
  163.            : (indice == LockMapIndex ? "ModLock"
  164.               : (indice == ControlMapIndex ? "ModControl"
  165.                  : (indice == Mod1MapIndex ? "Mod1"
  166.                     : (indice == Mod2MapIndex ? "Mod2"
  167.                        : (indice == Mod3MapIndex ? "Mod3"
  168.                           : (indice == Mod4MapIndex ? "Mod4"
  169.                              : (indice == Mod5MapIndex ? "Mod5"
  170.                                 : "???")))))))));
  171. }
  172.  
  173. /* Boy, I really wish C had local functions... */
  174. struct c_doesnt_have_closures   /* #### not yet used */
  175. {
  176.   int warned_about_overlapping_modifiers;
  177.   int warned_about_predefined_modifiers;
  178.   int warned_about_duplicate_modifiers;
  179.   int meta_bit;
  180.   int hyper_bit;
  181.   int super_bit;
  182.   int alt_bit;
  183.   int mode_bit;
  184. };
  185.  
  186. static void
  187. x_reset_modifier_mapping (struct device *d)
  188. {
  189.   Display *display = DEVICE_X_DISPLAY (d);
  190.   struct x_device *xd = DEVICE_X_DATA (d);
  191.   int modifier_index, modifier_key, column, mkpm;
  192.   int warned_about_overlapping_modifiers = 0;
  193.   int warned_about_predefined_modifiers = 0;
  194.   int warned_about_duplicate_modifiers = 0;
  195.   int meta_bit = 0;
  196.   int hyper_bit = 0;
  197.   int super_bit = 0;
  198.   int alt_bit = 0;
  199.   int mode_bit = 0;
  200.  
  201.   xd->lock_interpretation = 0;
  202.  
  203.   if (xd->x_modifier_keymap)
  204.     XFreeModifiermap (xd->x_modifier_keymap);
  205.  
  206.   x_reset_key_mapping (d);
  207.  
  208.   xd->x_modifier_keymap = XGetModifierMapping (display);
  209.  
  210.   /* Boy, I really wish C had local functions...
  211.    */
  212.  
  213.   /* The call to warn_when_safe must be on the same line as the string or
  214.      make-msgfile won't pick it up properly (the newline doesn't confuse
  215.      it, but the backslash does). */
  216.  
  217. #define modwarn(name,old,other)                        \
  218.   warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is generated by %s.",    \
  219.           name, code, index_to_name (old), other),        \
  220.   warned_about_overlapping_modifiers = 1
  221.  
  222. #define modbarf(name,other)                            \
  223.   warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is nonsensical.", \
  224.           name, code, other),                        \
  225.   warned_about_predefined_modifiers = 1
  226.  
  227. #define check_modifier(name,mask)                          \
  228.   if ((1<<modifier_index) != mask)                          \
  229.     warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is nonsensical.", \
  230.             name, code, index_to_name (modifier_index)),          \
  231.     warned_about_predefined_modifiers = 1
  232.  
  233. #define store_modifier(name,old)                       \
  234.   if (old && old != modifier_index)                       \
  235.     warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates both %s and %s, which is nonsensical.",\
  236.             name, code, index_to_name (old),               \
  237.             index_to_name (modifier_index)),               \
  238.     warned_about_duplicate_modifiers = 1;                   \
  239.   if (modifier_index == ShiftMapIndex) modbarf (name,"ModShift");       \
  240.   else if (modifier_index == LockMapIndex) modbarf (name,"ModLock");       \
  241.   else if (modifier_index == ControlMapIndex) modbarf (name,"ModControl"); \
  242.   else if (sym == XK_Mode_switch)                       \
  243.     mode_bit = modifier_index; /* Mode_switch is special, see below... */  \
  244.   else if (modifier_index == meta_bit && old != meta_bit)           \
  245.     modwarn (name, meta_bit, "Meta");                       \
  246.   else if (modifier_index == super_bit && old != super_bit)           \
  247.     modwarn (name, super_bit, "Super");                       \
  248.   else if (modifier_index == hyper_bit && old != hyper_bit)           \
  249.     modwarn (name, hyper_bit, "Hyper");                       \
  250.   else if (modifier_index == alt_bit && old != alt_bit)               \
  251.     modwarn (name, alt_bit, "Alt");                       \
  252.   else                                       \
  253.     old = modifier_index;
  254.  
  255.   mkpm = xd->x_modifier_keymap->max_keypermod;
  256.   for (modifier_index = 0; modifier_index < 8; modifier_index++)
  257.     for (modifier_key = 0; modifier_key < mkpm; modifier_key++) {
  258.       KeySym last_sym = 0;
  259.       for (column = 0; column < 4; column += 2) {
  260.     KeyCode code = xd->x_modifier_keymap->modifiermap[modifier_index * mkpm
  261.                               + modifier_key];
  262.     KeySym sym = (code ? XKeycodeToKeysym (display, code, column) : 0);
  263.     if (sym == last_sym) continue;
  264.     last_sym = sym;
  265.     switch (sym) {
  266.     case XK_Mode_switch:store_modifier ("Mode_switch", mode_bit); break;
  267.     case XK_Meta_L:     store_modifier ("Meta_L", meta_bit); break;
  268.     case XK_Meta_R:     store_modifier ("Meta_R", meta_bit); break;
  269.     case XK_Super_L:    store_modifier ("Super_L", super_bit); break;
  270.     case XK_Super_R:    store_modifier ("Super_R", super_bit); break;
  271.     case XK_Hyper_L:    store_modifier ("Hyper_L", hyper_bit); break;
  272.     case XK_Hyper_R:    store_modifier ("Hyper_R", hyper_bit); break;
  273.     case XK_Alt_L:      store_modifier ("Alt_L", alt_bit); break;
  274.     case XK_Alt_R:      store_modifier ("Alt_R", alt_bit); break;
  275.     case XK_Control_L:  check_modifier ("Control_L", ControlMask); break;
  276.     case XK_Control_R:  check_modifier ("Control_R", ControlMask); break;
  277.     case XK_Shift_L:    check_modifier ("Shift_L", ShiftMask); break;
  278.     case XK_Shift_R:    check_modifier ("Shift_R", ShiftMask); break;
  279.     case XK_Shift_Lock: check_modifier ("Shift_Lock", LockMask);
  280.       xd->lock_interpretation = XK_Shift_Lock; break;
  281.     case XK_Caps_Lock:  check_modifier ("Caps_Lock", LockMask);
  282.       xd->lock_interpretation = XK_Caps_Lock; break;
  283.  
  284.     /* It probably doesn't make any sense for a modifier bit to be
  285.        assigned to a key that is not one of the above, but OpenWindows
  286.        assigns modifier bits to a couple of random function keys for
  287.        no reason that I can discern, so printing a warning here would
  288.        be annoying.
  289.      */
  290.     }
  291.       }
  292.     }
  293. #undef store_modifier
  294. #undef check_modifier
  295. #undef modwarn
  296. #undef modbarf
  297.  
  298.   /* If there was no Meta key, then try using the Alt key instead.
  299.      If there is both a Meta key and an Alt key, then the Alt key
  300.      is not disturbed and remains an Alt key.
  301.    */
  302.   if (! meta_bit && alt_bit)
  303.     meta_bit = alt_bit, alt_bit = 0;
  304.  
  305.   /* mode_bit overrides everything, since it's processed down inside of
  306.      XLookupString() instead of by us.  If Meta and Mode_switch both
  307.      generate the same modifier bit (which is an error), then we don't
  308.      interpret that bit as Meta, because we can't make XLookupString()
  309.      not interpret it as Mode_switch; and interpreting it as both would
  310.      be totally wrong.
  311.    */
  312.   if (mode_bit)
  313.     {
  314.       CONST char *warn = 0;
  315.       if (mode_bit == meta_bit) warn = "Meta", meta_bit = 0;
  316.       else if (mode_bit == hyper_bit) warn = "Hyper", hyper_bit = 0;
  317.       else if (mode_bit == super_bit) warn = "Super", super_bit = 0;
  318.       else if (mode_bit == alt_bit) warn = "Alt", alt_bit = 0;
  319.       if (warn)
  320.     {
  321.       warn_when_safe
  322.         (Qkey_mapping, Qwarning,
  323.          "XEmacs:  %s is being used for both Mode_switch and %s.",
  324.          index_to_name (mode_bit), warn),
  325.         warned_about_overlapping_modifiers = 1;
  326.     }
  327.     }
  328. #undef index_to_name
  329.  
  330.   xd->MetaMask   = (meta_bit   ? (1 << meta_bit)  : 0);
  331.   xd->HyperMask  = (hyper_bit  ? (1 << hyper_bit) : 0);
  332.   xd->SuperMask  = (super_bit  ? (1 << super_bit) : 0);
  333.   xd->AltMask    = (alt_bit    ? (1 << alt_bit)   : 0);
  334.   xd->ModeMask   = (mode_bit   ? (1 << mode_bit)  : 0); /* unused */
  335.  
  336.  
  337.   if (warned_about_overlapping_modifiers)
  338.     warn_when_safe (Qkey_mapping, Qwarning, "\n\
  339.     Two distinct modifier keys (such as Meta and Hyper) cannot generate\n\
  340.     the same modifier bit, because Emacs won't be able to tell which\n\
  341.     modifier was actually held down when some other key is pressed.  It\n\
  342.     won't be able to tell Meta-x and Hyper-x apart, for example.  Change\n\
  343.     one of these keys to use some other modifier bit.  If you intend for\n\
  344.     these keys to have the same behavior, then change them to have the\n\
  345.     same keysym as well as the same modifier bit.");
  346.  
  347.   if (warned_about_predefined_modifiers)
  348.     warn_when_safe (Qkey_mapping, Qwarning, "\n\
  349.     The semantics of the modifier bits ModShift, ModLock, and ModControl\n\
  350.     are predefined.  It does not make sense to assign ModControl to any\n\
  351.     keysym other than Control_L or Control_R, or to assign any modifier\n\
  352.     bits to the \"control\" keysyms other than ModControl.  You can't\n\
  353.     turn a \"control\" key into a \"meta\" key (or vice versa) by simply\n\
  354.     assigning the key a different modifier bit.  You must also make that\n\
  355.     key generate an appropriate keysym (Control_L, Meta_L, etc).");
  356.  
  357.   /* Don\'t need to say anything more for warned_about_duplicate_modifiers. */
  358.  
  359.   if (warned_about_overlapping_modifiers || warned_about_predefined_modifiers)
  360.     warn_when_safe (Qkey_mapping, Qwarning, "\n\
  361.     The meanings of the modifier bits Mod1 through Mod5 are determined\n\
  362.     by the keysyms used to control those bits.  Mod1 does NOT always\n\
  363.     mean Meta, although some non-ICCCM-compliant programs assume that.");
  364. }
  365.  
  366. void
  367. x_init_modifier_mapping (struct device *d)
  368. {
  369.   DEVICE_X_DATA (d)->x_keysym_map = 0;
  370.   DEVICE_X_DATA (d)->x_modifier_keymap = 0;
  371.   x_reset_modifier_mapping (d);
  372. }
  373.  
  374. static int
  375. x_key_is_modifier_p (KeyCode keycode, struct device *d)
  376. {
  377.   struct x_device *xd = DEVICE_X_DATA (d);
  378.   KeySym *syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
  379.                     xd->x_keysym_map_keysyms_per_code];
  380.   int i;
  381.   for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
  382.     if (IsModifierKey (syms [i]) ||
  383.     syms [i] == XK_Mode_switch) /* why doesn't IsModifierKey count this? */
  384.       return 1;
  385.   return 0;
  386. }
  387.  
  388. /* key-handling code is always ugly.  It just ends up working out
  389.    that way.
  390.  
  391.    Here are some pointers:
  392.  
  393.    -- DOWN_MASK indicates which modifiers should be treated as "down"
  394.       when the corresponding upstroke happens.  It gets reset for
  395.       a particular modifier when that modifier goes up, and reset
  396.       for all modifiers when a non-modifier key is pressed.  Example:
  397.  
  398.       I press Control-A-Shift and then release Control-A-Shift.
  399.       I want the Shift key to be sticky but not the Control key.
  400.  
  401.    -- LAST_DOWNKEY and RELEASE_TIME are used to keep track of
  402.       auto-repeat -- see below.
  403.  
  404.    -- If a modifier key is sticky, I can unstick it by pressing
  405.       the modifier key again. */
  406.  
  407. static void
  408. x_handle_sticky_modifiers (XEvent *ev, struct device *d)
  409. {
  410.   struct x_device *xd = DEVICE_X_DATA (d);
  411.   KeyCode keycode = ev->xkey.keycode;
  412.   int type = ev->xany.type;
  413.   int is_modifier =
  414.     (type == KeyPress || type == KeyRelease) &&
  415.       x_key_is_modifier_p (keycode, d);
  416.     
  417.   if (!modifier_keys_are_sticky)
  418.     return;
  419.  
  420.   if (!is_modifier)
  421.     {
  422.       if (type == KeyPress && !xd->last_downkey)
  423.     xd->last_downkey = keycode;
  424.       else if (type == ButtonPress ||
  425.            (type == KeyPress && xd->last_downkey &&
  426.         (keycode != xd->last_downkey ||
  427.          ev->xkey.time != xd->release_time)))
  428.     {
  429.       xd->need_to_add_mask = 0;
  430.       xd->last_downkey = 0;
  431.     }
  432.       if (type == KeyPress)
  433.     xd->release_time = 0;
  434.       if (type == KeyPress || type == ButtonPress)
  435.     xd->down_mask = 0;
  436.  
  437.       ev->xkey.state |= xd->need_to_add_mask;
  438.  
  439.       if (type == KeyRelease && keycode == xd->last_downkey)
  440.     /* If I hold press-and-release the Control key and then press
  441.        and hold down the right arrow, I want it to auto-repeat
  442.        Control-Right.  On the other hand, if I do the same but
  443.        manually press the Right arrow a bunch of times, I want
  444.        to see one Control-Right and then a bunch of Rights.
  445.        This means that we need to distinguish between an
  446.        auto-repeated key and a key pressed and released a bunch
  447.        of times.
  448.  
  449.        Naturally, the designers of the X spec didn't see fit
  450.        to provide an obvious way to distinguish these cases.
  451.        So we assume that if the release and the next press
  452.        occur at the same time, the key was actually auto-
  453.        repeated.  Under Open-Windows, at least, this works.
  454.        */
  455.     xd->release_time = ev->xkey.time;
  456.     }
  457.   else
  458.     {
  459.       KeySym *syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
  460.                     xd->x_keysym_map_keysyms_per_code];
  461.       int i;
  462.  
  463. #define FROB(mask)                \
  464. do {                        \
  465.   if (type == KeyPress)                \
  466.     {                        \
  467.       /* If modifier key is already sticky,    \
  468.          then unstick it.  Note that we do    \
  469.          not test down_mask to deal with the    \
  470.      unlikely but possible case that the    \
  471.      modifier key auto-repeats. */        \
  472.       if (xd->need_to_add_mask & mask)        \
  473.     {                    \
  474.       xd->need_to_add_mask &= ~mask;    \
  475.       xd->down_mask &= ~mask;        \
  476.     }                    \
  477.       else                    \
  478.     xd->down_mask |= mask;            \
  479.     }                        \
  480.   else                        \
  481.     {                        \
  482.       if (xd->down_mask & mask)            \
  483.     {                    \
  484.       xd->down_mask &= ~mask;        \
  485.       xd->need_to_add_mask |= mask;        \
  486.     }                    \
  487.     }                        \
  488. } while (0)
  489.  
  490.       /* If a non-modifier key was pressed in the middle of a bunch
  491.      of modifiers, then it unsticks all the modifiers that were
  492.      previously pressed.  We cannot unstick the modifiers until
  493.      now because we want to check for auto-repeat of the
  494.      non-modifier key. */
  495.  
  496.       if (xd->last_downkey)
  497.     {
  498.       xd->last_downkey = 0;
  499.       xd->need_to_add_mask = 0;
  500.     }
  501.  
  502.       for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
  503.     {
  504.       if (syms[i] == XK_Control_L || syms[i] == XK_Control_R)
  505.         FROB (ControlMask);
  506.       if (syms[i] == XK_Shift_L || syms[i] == XK_Shift_R)
  507.         FROB (ShiftMask);
  508.       if (syms[i] == XK_Meta_L || syms[i] == XK_Meta_R)
  509.         FROB (xd->MetaMask);
  510.       if (syms[i] == XK_Super_L || syms[i] == XK_Super_R)
  511.         FROB (xd->SuperMask);
  512.       if (syms[i] == XK_Hyper_L || syms[i] == XK_Hyper_R)
  513.         FROB (xd->HyperMask);
  514.       if (syms[i] == XK_Alt_L || syms[i] == XK_Alt_R)
  515.         FROB (xd->AltMask);
  516.     }
  517.     }
  518. #undef FROB
  519. }
  520.  
  521. static void
  522. clear_sticky_modifiers (struct device *d)
  523. {
  524.   struct x_device *xd = DEVICE_X_DATA (d);
  525.  
  526.   xd->need_to_add_mask = 0;
  527.   xd->last_downkey = 0;
  528.   xd->release_time = 0;
  529.   xd->down_mask = 0;
  530. }
  531.  
  532. static int
  533. keysym_obeys_caps_lock_p (KeySym sym, struct device *d)
  534. {
  535.   struct x_device *xd = DEVICE_X_DATA (d);
  536.   /* Eeeeevil hack.  Don't apply caps-lock to things that aren't alphabetic
  537.      characters, where "alphabetic" means something more than simply A-Z.
  538.      That is, if caps-lock is down, typing ESC doesn't produce Shift-ESC.
  539.      But if shift-lock is down, then it does.
  540.    */
  541.   if (xd->lock_interpretation == XK_Shift_Lock)
  542.     return 1;
  543.   if (((sym >= XK_A) && (sym <= XK_Z)) ||
  544.       ((sym >= XK_a) && (sym <= XK_z)) ||
  545.       ((sym >= XK_Agrave) && (sym <= XK_Odiaeresis)) ||
  546.       ((sym >= XK_agrave) && (sym <= XK_odiaeresis)) ||
  547.       ((sym >= XK_Ooblique) && (sym <= XK_Thorn)) ||
  548.       ((sym >= XK_oslash) && (sym <= XK_thorn)))
  549.     return 1;
  550.   else
  551.     return 0;
  552. }
  553.  
  554. /* called from EmacsFrame.c (actually from Xt itself) when a
  555.    MappingNotify event is received.  For non-obvious reasons,
  556.    our event handler does not see these events, so we need a
  557.    special translation. */
  558. void
  559. emacs_Xt_mapping_action (Widget w, XEvent* event)
  560. {
  561.   struct device *d = get_device_from_display (event->xany.display);
  562. #if 0
  563.   /* nyet.  Now this is handled by Xt. */
  564.   XRefreshKeyboardMapping (&event->xmapping);
  565. #endif
  566.   /* xmodmap generates about a billion MappingKeyboard events, followed
  567.      by a single MappingModifier event, so it might be worthwhile to
  568.      take extra MappingKeyboard events out of the queue before requesting
  569.      the current keymap from the server.
  570.      */
  571.   if (event->xmapping.request == MappingKeyboard)
  572.     x_reset_key_mapping (d);
  573.   else if (event->xmapping.request == MappingModifier)
  574.     x_reset_modifier_mapping (d);
  575. }
  576.  
  577.  
  578. /************************************************************************/
  579. /*                  X to Emacs event conversion                         */
  580. /************************************************************************/
  581.  
  582. #if (defined(sun) || defined(__sun)) && defined(__GNUC__)
  583. # define SUNOS_GCC_L0_BUG
  584. #endif
  585.  
  586. #ifdef SUNOS_GCC_L0_BUG
  587. static void
  588. x_to_emacs_keysym_sunos_bug (Lisp_Object *return_value_sunos_bug, /* #### */
  589.                              XEvent *event, int simple_p)
  590. #else /* !SUNOS_GCC_L0_BUG */
  591. static Lisp_Object
  592. x_to_emacs_keysym (XEvent *event, int simple_p)
  593. #endif /* !SUNOS_GCC_L0_BUG */
  594.      /* simple_p means don't try too hard (ASCII only) */
  595. {
  596.   char *name;
  597.   KeySym keysym = 0;
  598.   struct device *d = get_device_from_display (event->xany.display);
  599.  
  600. #ifdef SUNOS_GCC_L0_BUG
  601. # define return(lose) \
  602.     do {*return_value_sunos_bug = (lose); goto return_it; } while (0)
  603. #endif
  604.  
  605.   XLookupString (&event->xkey, 0, 0, &keysym,
  606.          &DEVICE_X_X_COMPOSE_STATUS (d));
  607.   
  608.   if (keysym >= XK_exclam && keysym <= XK_asciitilde)
  609.     /* We must assume that the X keysym numbers for the ASCII graphic
  610.        characters are the same as their ASCII codes.  */
  611.     return (make_number (keysym));
  612.  
  613.   switch (keysym)
  614.     {
  615.       /* These would be handled correctly by the default case, but by
  616.      special-casing them here we don't garbage a string or call intern().
  617.      */
  618.     case XK_BackSpace:    return (QKbackspace);
  619.     case XK_Tab:    return (QKtab);
  620.     case XK_Linefeed:    return (QKlinefeed);
  621.     case XK_Return:    return (QKreturn);
  622.     case XK_Escape:    return (QKescape);
  623.     case XK_space:    return (QKspace);
  624.     case XK_Delete:    return (QKdelete);
  625.     case 0:        return (Qnil);
  626.     default:
  627.       if (simple_p) return (Qnil);
  628.       /* #### without return_value_sunos_bug, %l0 (GCC struct return pointer)
  629.        * ####  gets roached (top 8 bits cleared) around this call.
  630.        */
  631.       name = XKeysymToString (keysym);
  632.       if (!name || !name[0])    /* this shouldn't happen... */
  633.     {
  634.       char buf [255];
  635.       sprintf (buf, "unknown_keysym_0x%X", (int) keysym);
  636.       return (KEYSYM (buf));
  637.     }
  638.       /* If it's got a one-character name, that's good enough. */
  639.       if (!name[1]) return (make_number (name[0]));
  640.       
  641.       /* If it's in the "Keyboard" character set, downcase it.
  642.      The case of those keysyms is too totally random for us to
  643.      force anyone to remember them.
  644.      The case of the other character sets is significant, however.
  645.      */
  646.       if ((((unsigned int) keysym) & (~0xFF)) == ((unsigned int) 0xFF00))
  647.     {
  648.       char buf [255];
  649.       char *s1, *s2;
  650.       for (s1 = name, s2 = buf; *s1; s1++, s2++)
  651.         *s2 = tolower (* (unsigned char *) s1);
  652.       *s2 = 0;
  653.       return (KEYSYM (buf));
  654.     }
  655.       return (KEYSYM (name));
  656.     }
  657. #ifdef SUNOS_GCC_L0_BUG
  658. # undef return
  659.  return_it:
  660.   return;
  661. #endif
  662. }
  663.  
  664. #ifdef SUNOS_GCC_L0_BUG
  665. /* #### */
  666. static Lisp_Object
  667. x_to_emacs_keysym (XEvent *event, int simple_p)
  668. {
  669.   Lisp_Object return_value_sunos_bug;
  670.   x_to_emacs_keysym_sunos_bug (&return_value_sunos_bug, event, simple_p);
  671.   return (return_value_sunos_bug);
  672. }
  673. #endif
  674.  
  675. static void
  676. set_last_server_timestamp (struct device *d, XEvent *x_event)
  677. {
  678.   switch (x_event->xany.type)
  679.     {
  680.     case KeyPress:
  681.     case KeyRelease:
  682.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xkey.time;
  683.       break;
  684.  
  685.     case ButtonPress:
  686.     case ButtonRelease:
  687.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xbutton.time;
  688.       break;
  689.  
  690.     case MotionNotify:
  691.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xmotion.time;
  692.       break;
  693.  
  694.     case EnterNotify:
  695.     case LeaveNotify:
  696.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xcrossing.time;
  697.       break;
  698.       
  699.     case PropertyNotify:
  700.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xproperty.time;
  701.       break;
  702.  
  703.     case SelectionClear:
  704.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselectionclear.time;
  705.       break;
  706.  
  707.     case SelectionRequest:
  708.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselectionrequest.time;
  709.       break;
  710.  
  711.     case SelectionNotify:
  712.       DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselection.time;
  713.       break;
  714.     }
  715. }
  716.  
  717. static int
  718. x_event_to_emacs_event (XEvent *x_event, struct Lisp_Event *emacs_event)
  719. {
  720.   Display *display = x_event->xany.display;
  721.   struct device *d = get_device_from_display (display);
  722.   struct x_device *xd = DEVICE_X_DATA (d);
  723.   struct frame *sel_frame = XFRAME (DEVICE_SELECTED_FRAME (d));
  724.  
  725.   XSETDEVICE (emacs_event->device, d);
  726.   set_last_server_timestamp (d, x_event);
  727.  
  728.   switch (x_event->xany.type)
  729.     {
  730.     case KeyRelease:
  731.       x_handle_sticky_modifiers (x_event, d);
  732.       return 0;
  733.  
  734.     case KeyPress:
  735.     case ButtonPress:
  736.     case ButtonRelease:
  737.       {
  738.     unsigned int modifiers = 0;
  739.     int shift_p;
  740.     int lock_p;
  741. #ifdef EXTERNAL_WIDGET
  742.     struct frame *f = x_any_window_to_frame (d, x_event->xany.window);
  743. #endif
  744.     
  745.     /* If this is a synthetic KeyPress or Button event, and the user
  746.        has expressed a disinterest in this security hole, then drop
  747.        it on the floor.
  748.        */
  749.     if (((x_event->xany.type == KeyPress)
  750.          ? x_event->xkey.send_event
  751.          : x_event->xbutton.send_event)
  752. #ifdef EXTERNAL_WIDGET
  753.         /* ben: events get sent to an ExternalShell using XSendEvent.
  754.            This is not a perfect solution. */
  755.         && !FRAME_X_EXTERNAL_WINDOW_P (f)
  756. #endif
  757.         && !x_allow_sendevents)
  758.       return 0;
  759.     
  760.     x_handle_sticky_modifiers (x_event, d);
  761.  
  762.     shift_p = x_event->xkey.state & ShiftMask;
  763.     lock_p  = x_event->xkey.state & LockMask;
  764.  
  765.     if (x_event->xany.type == KeyPress)
  766.       DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) = x_event->xkey.time;
  767.     else
  768.       DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) = x_event->xbutton.time;
  769.     
  770.     /* Ignore the caps-lock key w.r.t. mouse presses and releases. */
  771.     if (x_event->xany.type != KeyPress)
  772.       lock_p = 0;
  773.     
  774.     if (x_event->xkey.state & ControlMask)     modifiers |= MOD_CONTROL;
  775.     if (x_event->xkey.state & xd->MetaMask)    modifiers |= MOD_META;
  776.     if (x_event->xkey.state & xd->SuperMask)   modifiers |= MOD_SUPER;
  777.     if (x_event->xkey.state & xd->HyperMask)   modifiers |= MOD_HYPER;
  778.     if (x_event->xkey.state & xd->AltMask)     modifiers |= MOD_ALT;
  779.  
  780.     /* Ignore the caps-lock key if any other modifiers are down; this is
  781.        so that Caps doesn't turn C-x into C-X, which would suck. */
  782.     if (modifiers)
  783.       {
  784.         x_event->xkey.state &= (~LockMask);
  785.         lock_p = 0;
  786.       }
  787.     
  788.     if (shift_p || lock_p)
  789.       modifiers |= MOD_SHIFT;
  790.     
  791.     DEVICE_X_MOUSE_TIMESTAMP (d) = DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d);
  792.  
  793.     switch (x_event->xany.type)
  794.       {
  795.       case KeyPress:
  796.         {
  797.           Lisp_Object keysym;
  798.           struct frame *frame = 0;
  799.           KeyCode keycode = x_event->xkey.keycode;
  800.           
  801. #ifdef I18N4
  802.           /* "A KeyPress event with a KeyCode of zero is used
  803.          exclusively as a signal that an input method has
  804.          composed input which can be returned..." -- X11
  805.          R5 Xlib - C Library manual, section 13.14.2.
  806.          We treat the signal itself as a magic event --
  807.          i.e., ignore it.
  808.          */
  809.           if (keycode == 0)
  810.         {
  811.           get_composed_input (&(x_event->xkey),
  812.                       FRAME_X_INPUT_CONTEXT (sel_frame));
  813.           return 0;
  814.         }
  815. #endif
  816.           if (x_key_is_modifier_p (keycode, d)) /* it's a modifier key */
  817.         return 0;
  818.           
  819.           if (!frame)
  820.         frame = x_any_window_to_frame (d, x_event->xkey.window);
  821.           
  822.           /* #### This doesn't seem right to me: shouldn't this be
  823.          "return 0"? */
  824.           if (! frame)
  825.         frame = sel_frame;
  826.           
  827.           /* At this point, FRAME_X_INPUT_P (frame) may be false.
  828.          That's ok, because you can get keyboard input even if you
  829.          don't have focus...
  830.          */
  831.           XSETFRAME (emacs_event->channel, frame);
  832.           keysym = x_to_emacs_keysym (x_event, 0);
  833.           
  834.           /* If the emacs keysym is nil, then that means that the
  835.          X keysym was NoSymbol, which probably means that
  836.          we're in the midst of reading a Multi_key sequence,
  837.          or a "dead" key prefix.  Ignore it. */
  838.           if (NILP (keysym))
  839.         return 0;
  840.           
  841.           /* More caps-lock garbage: caps-lock should *only* add
  842.          the shift modifier to two-case keys (that is, A-Z and
  843.          related characters).  So at this point (after looking
  844.          up the keysym) if the keysym isn't a dual-case
  845.          alphabetic, and if the caps lock key was down but the
  846.          shift key wasn't, then turn off the shift modifier.
  847.          Gag barf retch. */
  848.           /* #### type lossage: assuming equivalence of emacs and
  849.          X keysyms */
  850.           if (! keysym_obeys_caps_lock_p ((KeySym) XINT (keysym), d)
  851.           && lock_p
  852.           && !shift_p)
  853.         modifiers &= (~MOD_SHIFT);
  854.           
  855.           /* If this key contains two distinct keysyms, that is,
  856.          "shift" generates a different keysym than the
  857.          non-shifted key, then don't apply the shift modifier
  858.          bit: it's implicit.  Otherwise, if there would be no
  859.          other way to tell the difference between the shifted
  860.          and unshifted version of this key, apply the shift
  861.          bit.  Non-graphics, like Backspace and F1 get the
  862.          shift bit in the modifiers slot.  Neither the
  863.          characters "a", "A", "2", nor "@" normally have the
  864.          shift bit set.  However, "F1" normally does. */
  865.           if (modifiers & MOD_SHIFT)
  866.         {
  867.           KeySym top, bot;
  868.           if (x_event->xkey.state & xd->ModeMask)
  869.             bot = XLookupKeysym (&x_event->xkey, 2),
  870.             top = XLookupKeysym (&x_event->xkey, 3);
  871.           else
  872.             bot = XLookupKeysym (&x_event->xkey, 0),
  873.             top = XLookupKeysym (&x_event->xkey, 1);
  874.           if (top && bot && top != bot)
  875.             modifiers &= ~MOD_SHIFT;
  876.         }
  877.           emacs_event->event_type       = key_press_event;
  878.           emacs_event->timestamp       = x_event->xkey.time;
  879.           emacs_event->event.key.modifiers = modifiers;
  880.           emacs_event->event.key.keysym   = keysym;
  881.           break;
  882.         }
  883.       case ButtonPress:
  884.       case ButtonRelease:
  885.         {
  886.           struct frame *frame =
  887.         x_window_to_frame (d, x_event->xbutton.window);
  888.           if (! frame)
  889.         return 0;    /* not for us */
  890.           XSETFRAME (emacs_event->channel, frame);
  891.         }
  892.         
  893.         if (x_event->type == ButtonPress)
  894.           emacs_event->event_type    = button_press_event;
  895.         else emacs_event->event_type = button_release_event;
  896.         emacs_event->timestamp            = x_event->xbutton.time;
  897.         emacs_event->event.button.modifiers = modifiers;
  898.         emacs_event->event.button.button    = x_event->xbutton.button;
  899.         emacs_event->event.button.x         = x_event->xbutton.x;
  900.         emacs_event->event.button.y         = x_event->xbutton.y;
  901.         break;
  902.       }
  903.       }
  904.       break;
  905.       
  906.     case MotionNotify:
  907.       {
  908.     Window w = x_event->xmotion.window;
  909.     struct frame *frame = x_window_to_frame (d, w);
  910.     XEvent event2;
  911.     
  912.     if (! frame)
  913.       return 0; /* not for us */
  914.     
  915.     /* We use MotionHintMask, so we will get only one motion event
  916.        until the next time we call XQueryPointer or the user clicks
  917.        the mouse.  So call XQueryPointer now (meaning that the event
  918.        will be in sync with the server just before Fnext_event()
  919.        returns).  If the mouse is still in motion, then the server
  920.        will immediately generate exactly one more motion event, which
  921.        will be on the queue waiting for us next time around.
  922.        */
  923.     event2 = *x_event;
  924.     if (XQueryPointer (x_event->xmotion.display, event2.xmotion.window,
  925.                &event2.xmotion.root, &event2.xmotion.subwindow,
  926.                &event2.xmotion.x_root, &event2.xmotion.y_root,
  927.                &event2.xmotion.x, &event2.xmotion.y,
  928.                &event2.xmotion.state))
  929.       *x_event = event2;
  930.     
  931.     DEVICE_X_MOUSE_TIMESTAMP (d) = x_event->xmotion.time;
  932.     
  933.     XSETFRAME (emacs_event->channel, frame);
  934.     emacs_event->event_type      = pointer_motion_event;
  935.     emacs_event->timestamp      = x_event->xmotion.time;
  936.     emacs_event->event.motion.x = x_event->xmotion.x;
  937.     emacs_event->event.motion.y = x_event->xmotion.y;
  938.     {
  939.       unsigned int modifiers = 0;
  940.       if (x_event->xmotion.state & ShiftMask)   modifiers |= MOD_SHIFT;
  941.       if (x_event->xmotion.state & ControlMask) modifiers |= MOD_CONTROL;
  942.       if (x_event->xmotion.state & xd->MetaMask)    modifiers |= MOD_META;
  943.       if (x_event->xmotion.state & xd->SuperMask)   modifiers |= MOD_SUPER;
  944.       if (x_event->xmotion.state & xd->HyperMask)   modifiers |= MOD_HYPER;
  945.       if (x_event->xmotion.state & xd->AltMask)     modifiers |= MOD_ALT;
  946.       /* Currently ignores Shift_Lock but probably shouldn't
  947.          (but it definitely should ignore Caps_Lock). */
  948.       emacs_event->event.motion.modifiers = modifiers;
  949.     }
  950.       }
  951.       break;
  952.       
  953.     case ClientMessage:
  954. #ifdef I18N4
  955.       if (x_event->xclient.message_type == wc_atom)
  956.     {
  957.       struct frame *frame = 0;
  958.       
  959.       frame = x_any_window_to_frame (d, x_event->xkey.window);
  960.       if (! frame)
  961.         frame = sel_frame;
  962.       
  963.       This is currently broken.  Should be a key event, not a
  964.         wchar_event.
  965.           XSETFRAME (emacs_event->channel, frame);
  966.       emacs_event->event_type       = wchar_event;
  967.       emacs_event->timestamp        = x_event->xclient.data.l[0];
  968.       emacs_event->event.wchar.data = x_event->xclient.data.l[1];
  969.       break;
  970.     }
  971. #endif
  972.       /* Patch bogus TAKE_FOCUS messages from MWM; CurrentTime is passed as the
  973.      timestamp of the TAKE_FOCUS, which the ICCCM explicitly prohibits. */
  974.       if (x_event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d)
  975.       && x_event->xclient.data.l[0] == DEVICE_XATOM_WM_TAKE_FOCUS (d)
  976.       && x_event->xclient.data.l[1] == 0)
  977.     {
  978.       x_event->xclient.data.l[1] = DEVICE_X_LAST_SERVER_TIMESTAMP (d);
  979.     }
  980.       goto MAGIC;
  981.       
  982.     default:
  983.     MAGIC:
  984.       emacs_event->event_type = magic_event;
  985.       emacs_event->channel = Qnil; /* #### */
  986.       memcpy ((char *) &emacs_event->event.magic.underlying_x_event,
  987.           (char *) x_event,
  988.           sizeof (XEvent));
  989.       break;
  990.     }
  991.   return 1;
  992. }
  993.  
  994.  
  995. /************************************************************************/
  996. /*                           magic-event handling                       */
  997. /************************************************************************/
  998.  
  999. static void
  1000. handle_focus_event_1 (struct frame *f, int in_p)
  1001. {
  1002. #ifdef I18N4
  1003.   if (FRAME_X_INPUT_CONTEXT (f))
  1004.     {
  1005.       if (in_p)
  1006.     XSetICFocus (FRAME_X_INPUT_CONTEXT (f));
  1007.       else
  1008.     XUnsetICFocus (FRAME_X_INPUT_CONTEXT (f));
  1009.     }
  1010. #endif
  1011.   /* On focus change, clear all memory of sticky modifiers
  1012.      to avoid non-intuitive behavior. */
  1013.   clear_sticky_modifiers (XDEVICE (FRAME_DEVICE (f)));
  1014.  
  1015.   /* We don't want to handle the focus change now, because we might
  1016.      be in an accept-process-output, sleep-for, or sit-for.  So
  1017.      we enqueue it.
  1018.    */
  1019.   {
  1020.     Lisp_Object frm;
  1021.     
  1022.     XSETFRAME (frm, f);
  1023.     Fenqueue_eval_event (Qemacs_handle_focus_change,
  1024.              Fcons (frm, Fcons (FRAME_DEVICE (f),
  1025.                         in_p ? Qt : Qnil)));
  1026.   }
  1027. }
  1028.  
  1029. void emacs_Xt_handle_focus_event (XEvent *event);
  1030. void
  1031. emacs_Xt_handle_focus_event (XEvent *event)
  1032. {
  1033.   /*
  1034.    * It's curious that we're using x_any_window_to_frame() instead
  1035.    * of x_window_to_frame().  I don't know what the impact of this is.
  1036.    */
  1037.   
  1038.   struct frame *f =
  1039.     x_any_window_to_frame (get_device_from_display (event->xany.display),
  1040.                event->xfocus.window);
  1041.   if (!f)
  1042.     /* focus events are sometimes generated just before
  1043.        a frame is destroyed. */
  1044.     return;
  1045.   handle_focus_event_1 (f, event->xany.type == FocusIn);
  1046. }
  1047.  
  1048. static void
  1049. handle_map_event (XEvent *event)
  1050. {
  1051.   Lisp_Object frame = Qnil;
  1052.   struct frame *f =
  1053.     x_any_window_to_frame (get_device_from_display (event->xany.display),
  1054.                event->xmap.window);
  1055.  
  1056.   if (!f)
  1057.     return;
  1058.   XSETFRAME (frame, f);
  1059.   if (event->xany.type == MapNotify)
  1060.     {
  1061.       XWindowAttributes xwa;
  1062.  
  1063.       /* Bleagh!!!!!!  Apparently some window managers (e.g. MWM)
  1064.      send synthetic MapNotify events when a window is first
  1065.      created, EVENT IF IT'S CREATED ICONIFIED OR INVISIBLE.
  1066.      Or something like that.  We initially tried a different
  1067.      solution below, but that ran into a different window-
  1068.      manager bug.
  1069.  
  1070.      It seems that the only reliable way is to treat a
  1071.      MapNotify event as a "hint" that the window might or
  1072.      might not be visible, and check explicitly. */
  1073.  
  1074.       XGetWindowAttributes (event->xany.display, event->xmap.window,
  1075.                 &xwa);
  1076.       if (xwa.map_state != IsViewable)
  1077.     return;
  1078.  
  1079.       FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
  1080. #if 0
  1081.       /* Bleagh again!!!!  We initially tried the following hack
  1082.      around the MWM problem, but it turns out that TWM
  1083.      has a race condition when you un-iconify, where it maps
  1084.      the window and then tells the server that the window
  1085.      is un-iconified.  Usually, XEmacs wakes up between
  1086.      those two occurrences, and thus thinks that un-iconified
  1087.      windows are still iconified.
  1088.  
  1089.      Ah, the joys of X. */
  1090.  
  1091.       /* By Emacs definition, a frame that is iconified is not
  1092.      visible.  Marking a frame as visible will automatically cause
  1093.      frame-iconified-p to return nil, regardless of whether the
  1094.      frame is actually iconified.  Therefore, we have to ignore
  1095.      MapNotify events on iconified frames. (It's not obvious
  1096.      to me why these are being sent, but it happens at startup
  1097.      with frames that are initially iconified; perhaps they are
  1098.      synthetic MapNotify events coming from the window manager.)
  1099.      Note that `frame-iconified-p' queries the server
  1100.      to determine whether the frame is currently iconified,
  1101.      rather than consulting some internal (and likely
  1102.      inaccurate) state flag.  Therefore, ignoring the MapNotify
  1103.      is correct. */
  1104.       if (!f->visible && NILP (Fframe_iconified_p (frame)))
  1105. #endif
  1106.       if (!f->visible)
  1107.     {
  1108.       f->visible = 1;
  1109.       /* This improves the double flicker when uniconifying a frame
  1110.          some.  A lot of it is not showing a buffer which has changed
  1111.          while the frame was iconified.  To fix it further requires
  1112.          the good 'ol double redisplay structure. */
  1113.       MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
  1114.       run_hook_with_args (Qmap_frame_hook, 1, frame);
  1115. #ifdef EPOCH
  1116.       dispatch_epoch_event (event, Qx_map);
  1117. #endif
  1118.     }
  1119.     }
  1120.   else
  1121.     {
  1122.       FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
  1123.       if (f->visible)
  1124.     {
  1125.       f->visible = 0;
  1126.       run_hook_with_args (Qunmap_frame_hook, 1, frame);
  1127. #ifdef EPOCH
  1128.       dispatch_epoch_event (event, Qx_unmap);
  1129. #endif
  1130.     }
  1131.     }
  1132. }
  1133.  
  1134. static void
  1135. handle_client_message (XEvent *event)
  1136. {
  1137.   Display *display = event->xany.display;
  1138.   struct device *d = get_device_from_display (display);
  1139.   struct frame *f = x_any_window_to_frame (d, event->xclient.window);
  1140.   if (!f)
  1141.     return;
  1142.   if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
  1143.       event->xclient.data.l[0] == DEVICE_XATOM_WM_DELETE_WINDOW (d))
  1144.     {
  1145.       Lisp_Object frm, dev;
  1146.       Lisp_Object next;
  1147.       
  1148.       XSETFRAME (frm, f);
  1149.       XSETDEVICE (dev, d);
  1150.       next = next_frame (frm, Qt);
  1151.       /* WM_DELETE_WINDOW is a misc-user event, but other ClientMessages,
  1152.      such as WM_TAKE_FOCUS, are eval events.  That's because delete-window
  1153.      was probably executed with a mouse click, while the others could
  1154.      have been sent as a result of mouse motion or some other implicit
  1155.      action.  (Call this a "heuristic"...)  The reason for caring about
  1156.      this is so that clicking on the close-box will make emacs prompt
  1157.      using a dialog box instead of the minibuffer if there are unsaved
  1158.      buffers.
  1159.      */
  1160.       /* #### Review this. */
  1161.       if (EQ (next, frm) || EQ (frm, Vdefault_minibuffer_frame))
  1162.     enqueue_misc_user_event (Qdelete_device, dev);
  1163.       else
  1164.     enqueue_misc_user_event (Qdelete_frame, frm);
  1165.     }
  1166.   else if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
  1167.        event->xclient.data.l[0] == DEVICE_XATOM_WM_TAKE_FOCUS (d))
  1168.     {
  1169.       handle_focus_event_1 (f, 1);
  1170. #if 0
  1171.       /* If there is a dialog box up, focus on it.
  1172.      
  1173.      #### Actually, we're raising it too, which is wrong.  We should
  1174.      #### just focus on it, but lwlib doesn't currently give us an
  1175.      #### easy way to do that.  This should be fixed.
  1176.      */
  1177.       unsigned long take_focus_timestamp = event->xclient.data.l[1];
  1178.       Widget widget = lw_raise_all_pop_up_widgets ();
  1179.       if (widget)
  1180.     {
  1181.       /* kludge: raise_all returns bottommost widget, but we really
  1182.          want the topmost.  So just raise it for now. */
  1183.       XMapRaised (XtDisplay (widget), XtWindow (widget));
  1184.       /* Grab the focus with the timestamp of the TAKE_FOCUS. */
  1185.       XSetInputFocus (XtDisplay (widget), XtWindow (widget),
  1186.               RevertToParent, take_focus_timestamp);
  1187.     }
  1188. #endif
  1189.     }
  1190. #ifdef EPOCH
  1191.   dispatch_epoch_event (event, Qx_client_message);
  1192. #endif
  1193. }
  1194.  
  1195. static void
  1196. emacs_Xt_handle_magic_event (struct Lisp_Event *emacs_event)
  1197. {
  1198.   /* This function can GC */
  1199.   XEvent *event = (XEvent *) &emacs_event->event.magic.underlying_x_event;
  1200.   struct frame *f;
  1201.   struct device *d = XDEVICE (EVENT_DEVICE (emacs_event));
  1202.  
  1203.   switch (event->type)
  1204.     {
  1205.     case SelectionRequest:
  1206.       if (x_window_to_frame (d, event->xselectionrequest.owner))
  1207.     x_handle_selection_request (&event->xselectionrequest);
  1208.       break;
  1209.       
  1210.     case SelectionClear:
  1211.       if (x_window_to_frame (d, event->xselectionclear.window))
  1212.     x_handle_selection_clear (&event->xselectionclear);
  1213.       break;
  1214.       
  1215.     case SelectionNotify:
  1216.       if (x_window_to_frame (d, event->xselection.requestor))
  1217.     x_handle_selection_notify (&event->xselection);
  1218.       break;
  1219.       
  1220.     case PropertyNotify:
  1221.       if (x_window_to_frame (d, event->xproperty.window))
  1222.     {
  1223.       x_handle_property_notify (&event->xproperty);
  1224. #ifdef EPOCH
  1225.       dispatch_epoch_event (emacs_event, Qx_property_change);
  1226. #endif
  1227.     }
  1228.       break;
  1229.       
  1230.     case Expose:
  1231.       if ((f = x_window_to_frame (d, event->xexpose.window)))
  1232.     x_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
  1233.                    event->xexpose.width, event->xexpose.height);
  1234.       break;
  1235.       
  1236.     case GraphicsExpose: /* This occurs when an XCopyArea's source area was
  1237.                 obscured or not available. */
  1238.       if ((f = x_window_to_frame (d, event->xexpose.window)))
  1239.     x_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
  1240.                    event->xexpose.width, event->xexpose.height);
  1241.       break;
  1242.       
  1243.     case MapNotify:
  1244.     case UnmapNotify:
  1245.       handle_map_event (event);
  1246.       break;
  1247.       
  1248.     case EnterNotify:
  1249.       if ((f = x_any_window_to_frame (d, event->xcrossing.window)) &&
  1250.       (event->xcrossing.detail != NotifyInferior))
  1251.     {
  1252.       Lisp_Object frame;
  1253.       
  1254.       XSETFRAME (frame, f);
  1255.       /* FRAME_X_MOUSE_P (f) = 1; */
  1256.       run_hook_with_args (Qmouse_enter_frame_hook, 1, frame);
  1257.     }
  1258.       break;
  1259.       
  1260.     case LeaveNotify:
  1261.       if ((f = x_any_window_to_frame (d, event->xcrossing.window)) &&
  1262.       (event->xcrossing.detail != NotifyInferior))
  1263.     {
  1264.       Lisp_Object frame;
  1265.       
  1266.       XSETFRAME (frame, f);
  1267.       /* FRAME_X_MOUSE_P (f) = 0; */
  1268.       run_hook_with_args (Qmouse_leave_frame_hook, 1, frame);
  1269.     }
  1270.       break;
  1271.       
  1272.     case FocusIn:
  1273.     case FocusOut:
  1274. #ifdef EXTERNAL_WIDGET
  1275.       if (! (f = x_any_window_to_frame (d, event->xfocus.window)))
  1276.     break;
  1277.       
  1278.       /* External widget lossage: Ben said:
  1279.      YUCK.  The only way to make focus changes work properly is to
  1280.      completely ignore all FocusIn/FocusOut events and depend only
  1281.      on notifications from the ExternalClient widget. */
  1282.       if (FRAME_X_EXTERNAL_WINDOW_P (f))
  1283.     break;
  1284. #endif
  1285.       emacs_Xt_handle_focus_event (event);
  1286.       break;
  1287.       
  1288.     case ClientMessage:
  1289.       handle_client_message (event);
  1290.       break;
  1291.       
  1292. #if 0
  1293.       /* this is where we ought to be handling this event, but
  1294.      we don't see it here. --ben */
  1295.     case MappingNotify:    /* The user has run xmodmap */
  1296. #endif    
  1297.       
  1298.     case VisibilityNotify: /* window visiblity has changed */
  1299.       if (! (f = x_any_window_to_frame (d, event->xvisibility.window)))
  1300.     break;
  1301.       if (event->xvisibility.state == VisibilityUnobscured)
  1302.     FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
  1303.       else
  1304.     FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
  1305.       break;
  1306.       
  1307.     case ConfigureNotify:
  1308.       if (! (f = x_any_window_to_frame (d, event->xconfigure.window)))
  1309.     break;
  1310.       if (event->xconfigure.window != XtWindow (FRAME_X_SHELL_WIDGET (f)))
  1311.     break;
  1312.       FRAME_X_SHELL_WIDGET (f)->core.x = event->xconfigure.x;
  1313.       FRAME_X_SHELL_WIDGET (f)->core.y = event->xconfigure.y;
  1314.       break;
  1315.  
  1316.     default:
  1317.       break;
  1318.     }
  1319. }
  1320.  
  1321.  
  1322. /************************************************************************/
  1323. /*                timeout events                */
  1324. /************************************************************************/
  1325.  
  1326. static int timeout_id_tick;
  1327.  
  1328. /* Xt interval id's might not fit into an int (they're pointers, as it
  1329.    happens), so we need to provide a conversion list. */
  1330.  
  1331. struct Xt_timeout
  1332. {
  1333.   int id;
  1334.   XtIntervalId interval_id;
  1335.   struct Xt_timeout *next;
  1336. } *pending_timeouts, *completed_timeouts;
  1337.  
  1338. struct Xt_timeout_blocktype
  1339. {
  1340.   Blocktype_declare (struct Xt_timeout);
  1341. } *the_Xt_timeout_blocktype;
  1342.  
  1343. /* called by XtAppNextEvent() */
  1344. static void
  1345. Xt_timeout_callback (XtPointer closure, XtIntervalId *id)
  1346. {
  1347.   struct Xt_timeout *timeout = (struct Xt_timeout *) closure;
  1348.   struct Xt_timeout *t2 = pending_timeouts;
  1349.   /* Remove this one from the list of pending timeouts */
  1350.   if (t2 == timeout)
  1351.     pending_timeouts = pending_timeouts->next;
  1352.   else
  1353.     {
  1354.       while (t2->next && t2->next != timeout) t2 = t2->next;
  1355.       assert (t2->next);
  1356.       t2->next = t2->next->next;
  1357.     }
  1358.   /* Add this one to the list of completed timeouts */
  1359.   timeout->next = completed_timeouts;
  1360.   completed_timeouts = timeout;
  1361. }
  1362.  
  1363. static int
  1364. emacs_Xt_add_timeout (EMACS_TIME time)
  1365. {
  1366.   struct Xt_timeout *timeout = Blocktype_alloc (the_Xt_timeout_blocktype);
  1367.   EMACS_TIME current_time;
  1368.   int milliseconds;
  1369.  
  1370.   timeout->id = timeout_id_tick++;
  1371.   timeout->next = pending_timeouts;
  1372.   pending_timeouts = timeout;
  1373.   EMACS_GET_TIME (current_time);
  1374.   EMACS_SUB_TIME (time, time, current_time);
  1375.   milliseconds = EMACS_SECS (time) * 1000 +
  1376.     EMACS_USECS (time) / 1000;
  1377.   if (milliseconds < 1)
  1378.     milliseconds = 1;
  1379.   timeout->interval_id = XtAppAddTimeOut (Xt_app_con, milliseconds,
  1380.                       Xt_timeout_callback,
  1381.                       (XtPointer) timeout);
  1382.   return timeout->id;
  1383. }
  1384.  
  1385. static void
  1386. emacs_Xt_remove_timeout (int id)
  1387. {
  1388.   struct Xt_timeout *timeout, *t2;
  1389.  
  1390.   /* Find the timeout on the list of pending ones, if it's still there. */
  1391.   if (!pending_timeouts) return;
  1392.   if (id == pending_timeouts->id)
  1393.     {
  1394.       timeout = pending_timeouts;
  1395.       pending_timeouts = pending_timeouts->next;
  1396.     }
  1397.   else
  1398.     {
  1399.       t2 = pending_timeouts;
  1400.       while (t2->next && t2->next->id != id) t2 = t2->next;
  1401.       if (! t2->next) return;
  1402.       timeout = t2->next;
  1403.       t2->next = t2->next->next;
  1404.     }
  1405.  
  1406.   /* At this point, we've found the thing on the list of pending timeouts,
  1407.      and removed it.
  1408.    */
  1409.  
  1410.   XtRemoveTimeOut (timeout->interval_id);
  1411.   Blocktype_free (the_Xt_timeout_blocktype, timeout);
  1412. }
  1413.  
  1414. static void
  1415. Xt_timeout_to_emacs_event (struct Lisp_Event *emacs_event)
  1416. {
  1417.   struct Xt_timeout *timeout = completed_timeouts;
  1418.   assert (timeout);
  1419.   completed_timeouts = completed_timeouts->next;
  1420.   emacs_event->event_type = timeout_event;
  1421.   emacs_event->timestamp  = 0; /* #### wrong!! */
  1422.   emacs_event->event.timeout.interval_id = timeout->id;
  1423.   Blocktype_free (the_Xt_timeout_blocktype, timeout);
  1424. }
  1425.  
  1426.  
  1427. /************************************************************************/
  1428. /*            process and tty events                */
  1429. /************************************************************************/
  1430.  
  1431. struct what_is_ready_closure
  1432. {
  1433.   int fd;
  1434.   Lisp_Object what;
  1435.   XtInputId id;
  1436. };
  1437.  
  1438. static Lisp_Object *filedesc_with_input;
  1439. static struct what_is_ready_closure **filedesc_to_what_closure;
  1440.  
  1441. static void
  1442. init_what_input_once (void)
  1443. {
  1444.   int i;
  1445.  
  1446.   filedesc_with_input = (Lisp_Object *)
  1447.     xmalloc (MAXDESC * sizeof (Lisp_Object));
  1448.   filedesc_to_what_closure = (struct what_is_ready_closure **)
  1449.     xmalloc (MAXDESC * sizeof (struct what_is_ready_closure *));
  1450.  
  1451.   for (i = 0; i < MAXDESC; i++)
  1452.     {
  1453.       filedesc_to_what_closure[i] = 0;
  1454.       filedesc_with_input[i] = Qnil;
  1455.     }
  1456.  
  1457.   process_events_occurred = 0;
  1458.   tty_events_occurred = 0;
  1459. }
  1460.  
  1461. static void
  1462. mark_what_as_being_ready (struct what_is_ready_closure *closure)
  1463. {
  1464.   if (NILP (filedesc_with_input[closure->fd]))
  1465.     {
  1466.       filedesc_with_input[closure->fd] = closure->what;
  1467.       if (PROCESSP (closure->what))
  1468.       /* Don't increment this if the current process is already marked
  1469.        *  as having input. */
  1470.     process_events_occurred++;
  1471.       else
  1472.     tty_events_occurred++;
  1473.     }
  1474. }
  1475.  
  1476. static void
  1477. Xt_what_callback (void *closure, int *source, XtInputId *id)
  1478. {
  1479.   /* If closure is 0, then we got a fake event from a signal handler.
  1480.      The only purpose of this is to make XtAppProcessEvent() stop
  1481.      blocking. */
  1482.   if (closure)
  1483.     mark_what_as_being_ready ((struct what_is_ready_closure *) closure);
  1484.   else
  1485.     {
  1486.       fake_event_occurred++;
  1487.       drain_signal_event_pipe ();
  1488.     }
  1489. }
  1490.  
  1491. static void
  1492. select_filedesc (int fd, Lisp_Object what)
  1493. {
  1494.   struct what_is_ready_closure *closure;
  1495.  
  1496.   /* If somebody is trying to select something that's already selected
  1497.      for, then something went wrong.  The generic routines ought to
  1498.      detect this and error before here. */
  1499.   assert (!filedesc_to_what_closure[fd]);
  1500.  
  1501.   closure = (struct what_is_ready_closure *) xmalloc (sizeof (*closure));
  1502.   closure->fd = fd;
  1503.   closure->what = what;
  1504.   closure->id = 
  1505.     XtAppAddInput (Xt_app_con, fd,
  1506.            (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
  1507.            Xt_what_callback, closure);
  1508.   filedesc_to_what_closure[fd] = closure;
  1509. }
  1510.  
  1511. static void
  1512. unselect_filedesc (int fd)
  1513. {
  1514.   struct what_is_ready_closure *closure = filedesc_to_what_closure[fd];
  1515.  
  1516.   assert (closure);
  1517.   if (!NILP (filedesc_with_input[fd]))
  1518.     {
  1519.       /* We are unselecting this process before we have drained the rest of
  1520.      the input from it, probably from status_notify() in the command loop.
  1521.      This can happen like so:
  1522.  
  1523.       - We are waiting in XtAppNextEvent()
  1524.       - Process generates output
  1525.       - Process is marked as being ready
  1526.       - Process dies, SIGCHLD gets generated before we return (!?)
  1527.         It could happen I guess.
  1528.       - sigchld_handler() marks process as dead
  1529.       - Somehow we end up getting a new KeyPress event on the queue
  1530.         at the same time (I'm really so sure how that happens but I'm
  1531.         not sure it can't either so let's assume it can...).
  1532.       - Key events have priority so we return that instead of the proc.
  1533.       - Before dispatching the lisp key event we call status_notify()
  1534.       - Which deselects the process that SIGCHLD marked as dead.
  1535.  
  1536.      Thus we never remove it from _with_input and turn it into a lisp
  1537.      event, so we need to do it here.  But this does not mean that we're
  1538.      throwing away the last block of output - status_notify() has already
  1539.      taken care of running the proc filter or whatever.
  1540.        */
  1541.       filedesc_with_input[fd] = Qnil;
  1542.       if (PROCESSP (closure->what))
  1543.     {
  1544.       assert (process_events_occurred > 0);
  1545.       process_events_occurred--;
  1546.     }
  1547.       else
  1548.     {
  1549.       assert (tty_events_occurred > 0);
  1550.       tty_events_occurred--;
  1551.     }
  1552.     }
  1553.   XtRemoveInput (closure->id);
  1554.   xfree (closure);
  1555.   filedesc_to_what_closure[fd] = 0;
  1556. }
  1557.  
  1558. static void
  1559. emacs_Xt_select_process (struct Lisp_Process *p)
  1560. {
  1561.   int infd, outfd;
  1562.   Lisp_Object process;
  1563.  
  1564.   get_process_file_descriptors (p, &infd, &outfd);
  1565.   XSETPROCESS (process, p);
  1566.   select_filedesc (infd, process);
  1567. }
  1568.  
  1569. static void
  1570. emacs_Xt_unselect_process (struct Lisp_Process *p)
  1571. {
  1572.   int infd, outfd;
  1573.  
  1574.   get_process_file_descriptors (p, &infd, &outfd);
  1575.  
  1576.   /* If the infd is < 0, it has already been deleted, and Xt will freak
  1577.      because its calls to select() will fail.
  1578.    */
  1579.   if (infd < 0)
  1580.     abort ();
  1581.   unselect_filedesc (infd);
  1582. }
  1583.  
  1584. /* This is called from GC when a process object is about to be freed.
  1585.    If we've still got pointers to it in this file, we're gonna lose hard.
  1586.  */
  1587. void
  1588. debug_process_finalization (struct Lisp_Process *p)
  1589. {
  1590. #if 0 /* #### */
  1591.   int i;
  1592.   int infd, outfd;
  1593.   get_process_file_descriptors (p, &infd, &outfd);
  1594.   /* if it still has fds, then it hasn't been killed yet. */
  1595.   assert (infd < 0);
  1596.   assert (outfd < 0);
  1597.   /* Better not still be in the "with input" table; we know it's got no fds. */
  1598.   for (i = 0; i < MAXDESC; i++)
  1599.     {
  1600.       Lisp_Object process = filedesc_fds_with_input [i];
  1601.       assert (!PROCESSP (process) || XPROCESS (process) != p);
  1602.     }
  1603. #endif
  1604. }
  1605.  
  1606. static void
  1607. Xt_process_to_emacs_event (struct Lisp_Event *emacs_event)
  1608. {
  1609.   int i;
  1610.   Lisp_Object process;
  1611.  
  1612.   assert (process_events_occurred > 0);
  1613.   for (i = 0; i < MAXDESC; i++)
  1614.     {
  1615.       process = filedesc_with_input[i];
  1616.       if (PROCESSP (process))
  1617.     break;
  1618.     }
  1619.   assert (i < MAXDESC);
  1620.   filedesc_with_input[i] = Qnil;
  1621.   process_events_occurred--;
  1622.   emacs_event->event_type = process_event;
  1623.   emacs_event->timestamp  = 0; /* #### */
  1624.   emacs_event->event.process.process = process;
  1625. }
  1626.  
  1627. static void
  1628. emacs_Xt_select_device (struct device *d)
  1629. {
  1630.   Lisp_Object device;
  1631.   int infd;
  1632.  
  1633.   if (DEVICE_IS_X (d))
  1634.     return; /* X devices are automatically selected for when we
  1635.            initialize them in Xt */
  1636.   XSETDEVICE (device, d);
  1637.   infd = DEVICE_INFD (d);
  1638.   select_filedesc (infd, device);
  1639.   FD_SET (infd, &tty_device_mask);
  1640. }
  1641.  
  1642. static void
  1643. emacs_Xt_unselect_device (struct device *d)
  1644. {
  1645.   int infd;
  1646.  
  1647.   if (DEVICE_IS_X (d))
  1648.     return;
  1649.   infd = DEVICE_INFD (d);
  1650.  
  1651.   /* If the infd is < 0, it has already been deleted, and Xt will freak
  1652.      because its calls to select() will fail.
  1653.    */
  1654.   if (infd < 0)
  1655.     abort ();
  1656.   unselect_filedesc (infd);
  1657.   FD_CLR (infd, &tty_device_mask);
  1658. }
  1659.  
  1660. /* read an event from a tty, if one is available.  Returns non-zero
  1661.    if an event was available.  Note that when this function is
  1662.    called, there should always be a tty marked as ready for input.
  1663.    However, the input condition might actually be EOF, so there
  1664.    may not really be any input available. (In this case,
  1665.    read_event_from_tty_or_stream_desc() will arrange for the TTY device
  1666.    to be deleted.) */
  1667.  
  1668. static int
  1669. Xt_tty_to_emacs_event (struct Lisp_Event *emacs_event)
  1670. {
  1671.   int i;
  1672.  
  1673.   assert (tty_events_occurred > 0);
  1674.   for (i = 0; i < MAXDESC; i++)
  1675.     {
  1676.       Lisp_Object device = filedesc_with_input[i];
  1677.       if (DEVICEP (device))
  1678.     {
  1679.       assert (tty_events_occurred > 0);
  1680.       tty_events_occurred--;
  1681.       filedesc_with_input[i] = Qnil;
  1682.       if (read_event_from_tty_or_stream_desc (emacs_event,
  1683.                           XDEVICE (device), i))
  1684.         return 1;
  1685.     }
  1686.     }
  1687.  
  1688.   return 0;
  1689. }
  1690.  
  1691.  
  1692. /************************************************************************/
  1693. /*        debugging functions to decipher an event        */
  1694. /************************************************************************/
  1695.  
  1696. #ifdef DEBUG_XEMACS
  1697. #include "xintrinsicp.h"    /* only describe_event() needs this */
  1698. #include <X11/Xproto.h>        /* only describe_event() needs this */
  1699.  
  1700. static void
  1701. describe_event_window (Window window, Display *display)
  1702. {
  1703.   struct frame *f;
  1704.   Widget w;
  1705.   stderr_out ("   window: 0x%x", (int) window);
  1706.   w = XtWindowToWidget (display, window);
  1707.   if (w)
  1708.     stderr_out (" %s", w->core.widget_class->core_class.class_name);
  1709.   f = x_any_window_to_frame (get_device_from_display (display), window);
  1710.   if (f)
  1711.     stderr_out (" \"%s\"", string_ext_data (XSTRING (f->name)));
  1712.   stderr_out ("\n");
  1713. }
  1714.  
  1715. static void
  1716. describe_event (XEvent *event)
  1717. {
  1718.   char buf[100];
  1719.   struct device *d = get_device_from_display (event->xany.display);
  1720.  
  1721.   sprintf (buf, "%s%s", x_event_name (event->xany.type),
  1722.        event->xany.send_event ? " (send)" : "");
  1723.   stderr_out ("%-30s", buf);
  1724.   switch (event->xany.type)
  1725.     {
  1726.     case FocusIn:
  1727.     case FocusOut:
  1728.       describe_event_window (event->xfocus.window, event->xfocus.display);
  1729.       stderr_out ("     mode: %s\n",
  1730.           (event->xfocus.mode == NotifyNormal ? "Normal"
  1731.            :(event->xfocus.mode == NotifyGrab ? "Grab"
  1732.              :(event->xfocus.mode == NotifyUngrab ? "Ungrab"
  1733.                :(event->xfocus.mode == NotifyWhileGrabbed ?
  1734.              "WhileGrabbed" : "?")))));
  1735.       stderr_out ("   detail: %s\n",
  1736.           (event->xfocus.detail == NotifyAncestor ? "Ancestor"
  1737.            :(event->xfocus.detail == NotifyVirtual ? "Virtual"
  1738.              :(event->xfocus.detail == NotifyInferior ? "Inferior"
  1739.                :(event->xfocus.detail == NotifyNonlinear ? "Nonlinear"
  1740.              :(event->xfocus.detail == NotifyNonlinearVirtual ?
  1741.                "NonlinearVirtual"
  1742.                :(event->xfocus.detail == NotifyPointer ? "Pointer"
  1743.                  :(event->xfocus.detail == NotifyPointerRoot ?
  1744.                    "PointerRoot"
  1745.                    :(event->xfocus.detail == NotifyDetailNone ?
  1746.                  "DetailNone" : "?")))))))));
  1747.       break;
  1748.       
  1749.     case KeyPress:
  1750.       {
  1751.     Lisp_Object keysym;
  1752.     describe_event_window (event->xkey.window, event->xkey.display);
  1753.     stderr_out ("   subwindow: %ld\n", event->xkey.subwindow);
  1754.     stderr_out ("    state: ");
  1755.     if (event->xkey.state & ShiftMask)   stderr_out ("Shift ");
  1756.     if (event->xkey.state & LockMask)    stderr_out ("Lock ");
  1757.     if (event->xkey.state & ControlMask) stderr_out ("Control ");
  1758.     if (event->xkey.state & Mod1Mask)    stderr_out ("Mod1 ");
  1759.     if (event->xkey.state & Mod2Mask)    stderr_out ("Mod2 ");
  1760.     if (event->xkey.state & Mod3Mask)    stderr_out ("Mod3 ");
  1761.     if (event->xkey.state & Mod4Mask)    stderr_out ("Mod4 ");
  1762.     if (event->xkey.state & Mod5Mask)    stderr_out ("Mod5 ");
  1763. #if 0 /* Apparently these don't exist? */
  1764.     if (event->xkey.state & MetaMask)    stderr_out ("Meta ");
  1765.     if (event->xkey.state & SuperMask)   stderr_out ("Super ");
  1766.     if (event->xkey.state & HyperMask)   stderr_out ("Hyper ");
  1767.     if (event->xkey.state & AltMask)     stderr_out ("Alt ");
  1768.     if (event->xkey.state & ModeMask)    stderr_out ("Mode_switch ");
  1769. #endif
  1770.     
  1771.     if (! event->xkey.state)
  1772.       stderr_out ("vanilla\n");
  1773.     else
  1774.       stderr_out ("\n");
  1775.     if (x_key_is_modifier_p (event->xkey.keycode, d))
  1776.       stderr_out ("   Modifier key");
  1777.     stderr_out ("  keycode: 0x%x\n", event->xkey.keycode);
  1778.     keysym = x_to_emacs_keysym (event, 0);
  1779.     if (INTP (keysym) && XINT (keysym) > 32 && XINT (keysym) <= 255)
  1780.       stderr_out ("   keysym: %c\n", XINT (keysym));
  1781.     else
  1782.       stderr_out ("   keysym: %s\n", string_data (XSYMBOL (keysym)->name));
  1783.       }
  1784.       break;
  1785.  
  1786.     case Expose:
  1787.       if (x_debug_events > 1)
  1788.     {
  1789.       describe_event_window (event->xexpose.window,
  1790.                  event->xexpose.display);
  1791.       stderr_out ("   region: %d %d %d %d\n", event->xexpose.x,
  1792.               event->xexpose.y, event->xexpose.width,
  1793.               event->xexpose.height);
  1794.       stderr_out ("    count: %d\n", event->xexpose.count);
  1795.     }
  1796.       else
  1797.     stderr_out ("\n");
  1798.       break;
  1799.  
  1800.     case GraphicsExpose:
  1801.       if (x_debug_events > 1)
  1802.     {
  1803.       describe_event_window (event->xgraphicsexpose.drawable,
  1804.                  event->xgraphicsexpose.display);
  1805.       stderr_out ("    major: %s\n",
  1806.               (event->xgraphicsexpose.major_code == X_CopyArea ?
  1807.                "CopyArea" :
  1808.                (event->xgraphicsexpose.major_code == X_CopyPlane ?
  1809.             "CopyPlane" : "?")));
  1810.       stderr_out ("   region: %d %d %d %d\n",
  1811.               event->xgraphicsexpose.x, event->xgraphicsexpose.y,
  1812.               event->xgraphicsexpose.width,
  1813.               event->xgraphicsexpose.height);
  1814.       stderr_out ("    count: %d\n", event->xgraphicsexpose.count);
  1815.     }
  1816.       else
  1817.     stderr_out ("\n");
  1818.       break;
  1819.  
  1820.     case EnterNotify:
  1821.     case LeaveNotify:
  1822.       if (x_debug_events > 1)
  1823.     {
  1824.       describe_event_window (event->xcrossing.window,
  1825.                  event->xcrossing.display);
  1826. #if 0
  1827.       stderr_out (" subwindow: 0x%x\n", event->xcrossing.subwindow);
  1828.       stderr_out ("      pos: %d %d\n", event->xcrossing.x,
  1829.               event->xcrossing.y);
  1830.       stderr_out (" root pos: %d %d\n",
  1831.               event->xcrossing.x_root, event->xcrossing.y_root);
  1832. #endif
  1833.       stderr_out ("     mode: %s\n",
  1834.               (event->xcrossing.mode == NotifyNormal ? "Normal"
  1835.                :(event->xcrossing.mode == NotifyGrab ? "Grab"
  1836.              :(event->xcrossing.mode == NotifyUngrab ? "Ungrab"
  1837.                :(event->xcrossing.mode == NotifyWhileGrabbed ?
  1838.                  "WhileGrabbed" : "?")))));
  1839.       stderr_out ("   detail: %s\n",
  1840.               (event->xcrossing.detail == NotifyAncestor ? "Ancestor"
  1841.                :(event->xcrossing.detail == NotifyVirtual ? "Virtual"
  1842.              :(event->xcrossing.detail == NotifyInferior ?
  1843.                "Inferior"
  1844.                :(event->xcrossing.detail == NotifyNonlinear ?
  1845.                  "Nonlinear"
  1846.                  :(event->xcrossing.detail ==
  1847.                    NotifyNonlinearVirtual ?
  1848.                    "NonlinearVirtual"
  1849.                    :(event->xcrossing.detail == NotifyPointer ?
  1850.                  "Pointer"
  1851.                  :(event->xcrossing.detail ==
  1852.                    NotifyPointerRoot ?
  1853.                    "PointerRoot"
  1854.                    :(event->xcrossing.detail ==
  1855.                      NotifyDetailNone ?
  1856.                      "DetailNone" : "?")))))))));
  1857.       stderr_out ("    focus: %d\n", event->xcrossing.focus);
  1858. #if 0
  1859.       stderr_out ("    state: 0x%x\n", event->xcrossing.state);
  1860. #endif
  1861.     }
  1862.       else
  1863.     stderr_out ("\n");
  1864.       break;
  1865.  
  1866.     case ConfigureNotify:
  1867.       if (x_debug_events > 1)
  1868.     {
  1869.       describe_event_window (event->xconfigure.window,
  1870.                  event->xconfigure.display);
  1871.       stderr_out ("    above: 0x%lx\n", event->xconfigure.above);
  1872.       stderr_out ("     size: %d %d %d %d\n", event->xconfigure.x,
  1873.               event->xconfigure.y,
  1874.               event->xconfigure.width, event->xconfigure.height);
  1875.       stderr_out ("  redirect: %d\n", event->xconfigure.override_redirect);
  1876.     }
  1877.       else
  1878.     stderr_out ("\n");
  1879.       break;
  1880.  
  1881.     case VisibilityNotify:
  1882.       if (x_debug_events > 1)
  1883.     {
  1884.       describe_event_window (event->xvisibility.window,
  1885.                  event->xvisibility.display);
  1886.       stderr_out ("    state: %s\n",
  1887.               (event->xvisibility.state == VisibilityUnobscured ?
  1888.                "Unobscured"
  1889.                :(event->xvisibility.state ==
  1890.              VisibilityPartiallyObscured ?
  1891.              "PartiallyObscured"
  1892.              :(event->xvisibility.state ==
  1893.                VisibilityFullyObscured ?
  1894.                "FullyObscured" : "?"))));
  1895.     }
  1896.       else
  1897.     stderr_out ("\n");
  1898.       break;
  1899.  
  1900.     case ClientMessage:
  1901.       {
  1902.     char *name = XGetAtomName (event->xclient.display,
  1903.                    event->xclient.message_type);
  1904.     stderr_out ("%s", name);
  1905.     if (!strcmp (name, "WM_PROTOCOLS"))
  1906.       {
  1907.         char *protname = XGetAtomName (event->xclient.display,
  1908.                        event->xclient.data.l[0]);
  1909.         stderr_out ("(%s)", protname);
  1910.         XFree (protname);
  1911.       }
  1912.     XFree (name);
  1913.     stderr_out ("\n");
  1914.     break;
  1915.       }
  1916.     
  1917.     default:
  1918.       stderr_out ("\n");
  1919.       break;
  1920.     }
  1921.  
  1922.   fflush (stdout);
  1923. }
  1924. #endif /* include describe_event definition */
  1925.  
  1926.  
  1927. /************************************************************************/
  1928. /*            get the next event from Xt            */
  1929. /************************************************************************/
  1930.  
  1931. static Lisp_Object dispatch_event_queue;
  1932. static struct Lisp_Event *dispatch_event_queue_tail;
  1933.  
  1934. static void
  1935. enqueue_Xt_dispatch_event (Lisp_Object event)
  1936. {
  1937.   enqueue_event (event, &dispatch_event_queue, &dispatch_event_queue_tail);
  1938. }
  1939.  
  1940. Lisp_Object
  1941. dequeue_Xt_dispatch_event (void)
  1942. {
  1943.   return dequeue_event (&dispatch_event_queue, &dispatch_event_queue_tail);
  1944. }
  1945.  
  1946. /* This business exists because menu events "happen" when
  1947.    menubar_selection_callback() is called from somewhere deep
  1948.    within XtAppProcessEvent in emacs_Xt_next_event().  The
  1949.    callback needs to terminate the modal loop in that function
  1950.    or else it will continue waiting until another event is
  1951.    received.
  1952.  
  1953.    Same business applies to scrollbar events. */
  1954.  
  1955. void
  1956. signal_special_Xt_user_event (Lisp_Object function, Lisp_Object object)
  1957. {
  1958.   Lisp_Object event;
  1959.  
  1960.   event = Fallocate_event ();
  1961.  
  1962.   XEVENT (event)->event_type = misc_user_event;
  1963.   XEVENT (event)->event.eval.function = function;
  1964.   XEVENT (event)->event.eval.object = object;
  1965.  
  1966.   enqueue_Xt_dispatch_event (event);
  1967. }  
  1968.  
  1969. static void
  1970. emacs_Xt_next_event (struct Lisp_Event *emacs_event)
  1971. {
  1972.  we_didnt_get_an_event:
  1973.  
  1974.   while (NILP (dispatch_event_queue) &&
  1975.      !completed_timeouts &&
  1976.      !fake_event_occurred &&
  1977.      !process_events_occurred &&
  1978.      !tty_events_occurred)
  1979.     {
  1980.  
  1981.       /* Stupid logic in XtAppProcessEvent() dictates that, if process
  1982.      events and X events are both available, the process event gets
  1983.      taken first.  This will cause an infinite loop if we're being
  1984.      called from Fdiscard_input().
  1985.        */
  1986.       if (XtAppPending (Xt_app_con) & XtIMXEvent)
  1987.         XtAppProcessEvent (Xt_app_con, XtIMXEvent);
  1988.       else
  1989.     {
  1990.       Lisp_Object rest;
  1991.  
  1992.       /* We're about to block.  Xt has a bug in it (big surprise,
  1993.          there) in that it blocks using select() and doesn't
  1994.          flush the Xlib output buffers (XNextEvent() does this
  1995.          automatically before blocking).  So it's necessary
  1996.          for us to do this ourselves.  If we don't do it, then
  1997.          display output may not be seen until the next time
  1998.          an X event is received. (This happens esp. with
  1999.          subprocess output that gets sent to a visible buffer.)
  2000.  
  2001.          #### The above comment may not have any validity. */
  2002.       for (rest = Vdevice_list ; !NILP (rest) ; rest = XCDR (rest))
  2003.         {
  2004.           struct device *d;
  2005.           d = XDEVICE (XCAR (rest));
  2006.  
  2007.           if (DEVICE_IS_X (d) && DEVICE_X_DISPLAY (d))
  2008.         /* emacs may be exiting */
  2009.         XFlush (DEVICE_X_DISPLAY (d));
  2010.         }
  2011.       XtAppProcessEvent (Xt_app_con, XtIMAll);
  2012.     }
  2013.     }
  2014.  
  2015.   if (!NILP (dispatch_event_queue))
  2016.     {
  2017.       Lisp_Object event, event2;
  2018.       XSETEVENT (event2, emacs_event);
  2019.       event = dequeue_Xt_dispatch_event ();
  2020.       Fcopy_event (event, event2);
  2021.       Fdeallocate_event (event);
  2022.     }
  2023.   else if (tty_events_occurred)
  2024.     {
  2025.       if (!Xt_tty_to_emacs_event (emacs_event))
  2026.     goto we_didnt_get_an_event;
  2027.     }
  2028.   else if (completed_timeouts)
  2029.     Xt_timeout_to_emacs_event (emacs_event);
  2030.   else if (fake_event_occurred)
  2031.     {
  2032.       /* A dummy event, so that a cycle of the command loop will
  2033.      occur. */
  2034.       fake_event_occurred = 0;
  2035.       emacs_event->event_type = eval_event;
  2036.       emacs_event->event.eval.function = Qidentity;
  2037.       emacs_event->event.eval.object = Qnil;
  2038.     }
  2039.   else /* if (process_events_occurred) */
  2040.     Xt_process_to_emacs_event (emacs_event);
  2041.  
  2042.   /* #### No I18N4 stuff here.  There appears to be no obvious place
  2043.      to call XFilterEvent().  I don't really understand that junk,
  2044.      anyway. */
  2045. }
  2046.  
  2047. void
  2048. emacs_Xt_event_handler (Widget wid /* unused */,
  2049.             XtPointer closure /* unused */,
  2050.             XEvent *event,
  2051.             Boolean *continue_to_dispatch /* unused */)
  2052. {
  2053.   Lisp_Object emacs_event = Fallocate_event ();
  2054.  
  2055. #ifdef DEBUG_XEMACS
  2056.   if (x_debug_events > 0)
  2057.     describe_event (event);
  2058. #endif
  2059.  
  2060.   if (x_event_to_emacs_event (event, XEVENT (emacs_event)))
  2061.     enqueue_Xt_dispatch_event (emacs_event);
  2062.   else
  2063.     Fdeallocate_event (emacs_event);
  2064. }
  2065.  
  2066.  
  2067. /************************************************************************/
  2068. /*                      input pending / C-g checking                    */
  2069. /************************************************************************/
  2070.  
  2071. static Bool
  2072. quit_char_predicate (Display *display, XEvent *event, XPointer data)
  2073. {
  2074.   struct device *d = get_device_from_display (display);
  2075.   struct x_device *xd = DEVICE_X_DATA (d);
  2076.   char c, quit_char;
  2077.   Bool *critical = (Bool *) data;
  2078.   Lisp_Object keysym;
  2079.  
  2080.   if (critical) *critical = False;
  2081.   if (event->type != KeyPress) return 0;
  2082.   if (! x_any_window_to_frame (d, event->xany.window)) return 0;
  2083.   if (event->xkey.state
  2084.       & (xd->MetaMask | xd->HyperMask | xd->SuperMask | xd->AltMask))
  2085.     return 0;
  2086.  
  2087.   /* This duplicates some code that exists elsewhere, but it's relatively
  2088.      fast and doesn't cons.
  2089.    */
  2090.   keysym = x_to_emacs_keysym (event, 1);
  2091.   if (NILP (keysym)) return 0;
  2092.   if (INTP (keysym))
  2093.     c = XINT (keysym);
  2094.   /* Highly doubtful that these are the quit character, but... */
  2095.   else if (EQ (keysym, QKbackspace))    c = '\b';
  2096.   else if (EQ (keysym, QKtab))        c = '\t';
  2097.   else if (EQ (keysym, QKlinefeed))    c = '\n';
  2098.   else if (EQ (keysym, QKreturn))    c = '\r';
  2099.   else if (EQ (keysym, QKescape))    c = 27;
  2100.   else if (EQ (keysym, QKspace))    c = ' ';
  2101.   else if (EQ (keysym, QKdelete))    c = 127;
  2102.   else return 0;
  2103.  
  2104.   if (event->xkey.state & xd->MetaMask)     c |= 0x80;
  2105.   if ((event->xkey.state & ControlMask) && !(c >= 'A' && c <= 'Z'))
  2106.     c &= 0x1F;            /* unshifted control characters */
  2107.   quit_char = DEVICE_QUIT_CHAR (d);
  2108.   if (c == quit_char)
  2109.     return True;
  2110.   /* If we've got Control-Shift-G instead of Control-G, that means
  2111.      we have a critical_quit.  Caps_Lock is its own modifier, so it
  2112.      won't cause ^G to act differently than before. */
  2113.   if (event->xkey.state & ControlMask)  c &= 0x1F;
  2114.   if (c == quit_char)
  2115.     {
  2116.       if (critical) *critical = True;
  2117.       return True;
  2118.     }
  2119.   return False;
  2120. }
  2121.  
  2122. /* This scans the X input queue for a KeyPress event that matches the
  2123.    quit character, and sets Vquit_flag.  This is called from the
  2124.    QUIT macro to determine whether we should quit.
  2125.  
  2126.    In a SIGIO world, this won't be called unless a SIGIO has happened
  2127.    since the last time we checked.
  2128.  
  2129.    In a non-SIGIO world, this is called from emacs_Xt_event_pending_p
  2130.    (which is called from input_pending_p).
  2131.  */
  2132. static void
  2133. x_check_for_quit_char (Display *display)
  2134. {
  2135.   XEvent event;
  2136.   int queued;
  2137.   Bool critical_quit = False;
  2138.   XEventsQueued (display, QueuedAfterReading);
  2139.   queued = XCheckIfEvent (display, &event,
  2140.               quit_char_predicate,
  2141.               (XtPointer)&critical_quit);
  2142.   if (queued)
  2143.     {
  2144.       Vquit_flag = (critical_quit ? Qcritical : Qt);
  2145.       /* don't put the event back onto the queue.  Those functions that
  2146.      wanted to read a ^G directly have arranged to do this. */
  2147.     }
  2148. }
  2149.  
  2150. static void
  2151. check_for_tty_quit_char (struct device *d)
  2152. {
  2153.   SELECT_TYPE temp_mask;
  2154.   int infd = DEVICE_INFD (d);
  2155.   char quit_char = DEVICE_QUIT_CHAR (d);
  2156.  
  2157.   FD_ZERO (&temp_mask);
  2158.   FD_SET (infd, &temp_mask);
  2159.  
  2160.   while (1)
  2161.     {
  2162.       Lisp_Object event;
  2163.       Emchar the_char;
  2164.  
  2165.       if (!poll_fds_for_input (temp_mask))
  2166.     return;
  2167.  
  2168.       event = Fallocate_event ();
  2169.       if (!read_event_from_tty_or_stream_desc (XEVENT (event), d, infd))
  2170.     /* EOF, or something ... */
  2171.     return;
  2172.       /* #### bogus.  quit-char should be allowed to be any sort
  2173.      of event. */
  2174.       the_char = event_to_character (XEVENT (event), 1, 0, 0);
  2175.       if (the_char >= 0 && the_char == quit_char)
  2176.     {
  2177.       Vquit_flag = Qt;
  2178.       /* do not queue the C-g.  See above. */
  2179.       return;
  2180.     }
  2181.  
  2182.       /* queue the read event to be read for real later. */
  2183.       enqueue_Xt_dispatch_event (event);
  2184.     }
  2185. }
  2186.  
  2187. static void
  2188. emacs_Xt_quit_p (void)
  2189. {
  2190.   Lisp_Object rest;
  2191.   DEVICE_LOOP (rest)
  2192.     {
  2193.       struct device *d;
  2194.       d = XDEVICE (XCAR (rest));
  2195.  
  2196.       if (!d->input_enabled)
  2197.     continue;
  2198.  
  2199.       if (DEVICE_IS_X (d) && DEVICE_X_DISPLAY (d)) /* emacs may be exiting */
  2200.     x_check_for_quit_char (DEVICE_X_DISPLAY (d));
  2201.       else if (DEVICE_IS_TTY (d))
  2202.     check_for_tty_quit_char (d);
  2203.     }
  2204. }
  2205.  
  2206. static void
  2207. drain_X_queue (void)
  2208. {
  2209.   while (XtAppPending (Xt_app_con) & XtIMXEvent)
  2210.     XtAppProcessEvent (Xt_app_con, XtIMXEvent);
  2211. }
  2212.  
  2213. static int
  2214. emacs_Xt_event_pending_p (int user_p)
  2215. {
  2216.   int tick_count_val;
  2217.  
  2218.   /* If `user_p' is false, then this function returns whether there are any
  2219.      X, timeout, or fd events pending (that is, whether emacs_Xt_next_event()
  2220.      would return immediately without blocking).
  2221.  
  2222.      if `user_p' is true, then this function returns whether there are any
  2223.      *user generated* events available (that is, whether there are keyboard
  2224.      or mouse-click events ready to be read).  This also implies that
  2225.      emacs_Xt_next_event() would not block.
  2226.  
  2227.      In a non-SIGIO world, this also checks whether the user has typed ^G,
  2228.      since this is a convenient place to do so.  We don't need to do this
  2229.      in a SIGIO world, since input causes an interrupt.
  2230.    */
  2231.  
  2232. #if 0
  2233.   /* I don't think there's any point to this and it will nullify
  2234.      the speed gains achieved by the sigio_happened checking below.
  2235.      Its only advantage is that it may possibly make C-g response
  2236.      a bit faster.  The C-g will be noticed within 0.25 second, anyway,
  2237.      even without this. */
  2238. #ifndef SIGIO
  2239.   /* First check for C-g if necessary */
  2240.   emacs_Xt_quit_p ();
  2241. #endif
  2242. #endif
  2243.  
  2244.   /* This function used to simply check whether there were any X
  2245.      events (or is user_p was 1, it iterated over all the pending
  2246.      X events using XCheckIfEvent(), looking for keystrokes and
  2247.      button events).  That worked in the old cheesoid event loop,
  2248.      which didn't go through XtAppDispatchEvent(), but it doesn't
  2249.      work any more -- X events may not result in anything.  For
  2250.      example, a button press in a blank part of the menubar appears
  2251.      as an X event but will not result in any Emacs events (a
  2252.      button press that activates the menubar results in an Emacs
  2253.      event through the stop_next_event mechanism).
  2254.  
  2255.      The only accurate way of determining whether these X events
  2256.      translate into Emacs events is to go ahead and dispatch them
  2257.      until there's something on the dispatch queue. */
  2258.  
  2259.   if (!NILP (dispatch_event_queue))
  2260.     {
  2261.       /* See if there are any user events already on the queue. */
  2262.       struct Lisp_Event *event;
  2263.  
  2264.       if (!user_p)
  2265.         return 1;
  2266.  
  2267.       for (event = XEVENT (dispatch_event_queue); event;
  2268.        event = event_next (event))
  2269.     if (command_event_p (event))
  2270.       return 1;
  2271.     }
  2272.  
  2273.   /* See if there's any TTY input available.
  2274.    */
  2275.   if (poll_fds_for_input (tty_device_mask))
  2276.     return 1;
  2277.  
  2278.   if (!user_p)
  2279.     {
  2280.       /* If not user_p and there are any timer or file-desc events
  2281.      pending, we know there will be an event so we're through. */
  2282.       XtInputMask pending_value;
  2283.  
  2284.       /* Note that formerly we just checked the value of XtAppPending()
  2285.      to determine if there was file-desc input.  This doesn't
  2286.      work any more with the signal_event_pipe; XtAppPending()
  2287.      will says "yes" in this case but there isn't really any
  2288.      input.  Another way of fixing this problem is for the
  2289.      signal_event_pipe to generate actual input in the form
  2290.      of an identity eval event or something. */
  2291.      
  2292.       if (poll_fds_for_input (process_only_mask))
  2293.     return 1;
  2294.  
  2295.       pending_value = XtAppPending (Xt_app_con);
  2296.  
  2297.       if (pending_value & XtIMTimer)
  2298.     return 1;
  2299.     }
  2300.  
  2301.   /* XtAppPending() can be super-slow, esp. over a network connection.
  2302.      Quantify results have indicated that in some cases the
  2303.      call to detect_input_pending() completely dominates the
  2304.      running time of redisplay().  Fortunately, in a SIGIO world
  2305.      we can more quickly determine whether there are any X events:
  2306.      if an event has happened since the last time we checked, then
  2307.      a SIGIO will have happened.  On a machine with broken SIGIO,
  2308.      we'll still be in an OK state -- the sigio_happened flag
  2309.      will get set at least once a second, so we'll be no more than
  2310.      one second behind reality. (In general it's OK if we
  2311.      erroneously report no input pending when input is actually
  2312.      pending() -- preemption is just a bit less efficient, that's
  2313.      all.  It's bad bad bad if you err the other way -- you've
  2314.      promised that `next-event' won't block but it actually will,
  2315.      and some action might get delayed until the next time you
  2316.      hit a key.)
  2317.      */
  2318.  
  2319.   /* quit_check_signal_tick_count is volatile so try to avoid race conditions
  2320.      by using a temporary variable */
  2321.   tick_count_val = quit_check_signal_tick_count;
  2322.   if (last_quit_check_signal_tick_count != tick_count_val)
  2323.     {
  2324.       struct Lisp_Event *event;
  2325.  
  2326.       last_quit_check_signal_tick_count = tick_count_val;
  2327.  
  2328.       /* We need to drain the entire queue now -- if we only
  2329.          drain part of it, we may later on end up with events
  2330.          actually pending but detect_input_pending() returning
  2331.          false because there wasn't another SIGIO. */
  2332.       drain_X_queue ();
  2333.  
  2334.       for (event = dispatch_event_queue_tail; event;
  2335.        event = event_next (event))
  2336.     if (!user_p || command_event_p (event))
  2337.       return 1;
  2338.     }
  2339.  
  2340.   return 0;
  2341. }
  2342.  
  2343.  
  2344. /************************************************************************/
  2345. /*                            initialization                            */
  2346. /************************************************************************/
  2347.  
  2348. void
  2349. syms_of_event_Xt (void)
  2350. {
  2351.   defsymbol (&Qkey_mapping, "key-mapping");
  2352. }
  2353.  
  2354. void
  2355. vars_of_event_Xt (void)
  2356. {
  2357.   dispatch_event_queue = Qnil;
  2358.   staticpro (&dispatch_event_queue);
  2359.  
  2360.   /* this function only makes safe calls */
  2361.   init_what_input_once ();
  2362.  
  2363.   Xt_event_stream =
  2364.     (struct event_stream *) xmalloc (sizeof (struct event_stream));
  2365.   Xt_event_stream->event_pending_p     = emacs_Xt_event_pending_p;
  2366.   Xt_event_stream->next_event_cb    = emacs_Xt_next_event;
  2367.   Xt_event_stream->handle_magic_event_cb= emacs_Xt_handle_magic_event;
  2368.   Xt_event_stream->add_timeout_cb     = emacs_Xt_add_timeout;
  2369.   Xt_event_stream->remove_timeout_cb     = emacs_Xt_remove_timeout;
  2370.   Xt_event_stream->select_device_cb     = emacs_Xt_select_device;
  2371.   Xt_event_stream->unselect_device_cb     = emacs_Xt_unselect_device;
  2372.   Xt_event_stream->select_process_cb     = emacs_Xt_select_process;
  2373.   Xt_event_stream->unselect_process_cb     = emacs_Xt_unselect_process;
  2374.   Xt_event_stream->quit_p_cb        = emacs_Xt_quit_p;
  2375.  
  2376.   DEFVAR_BOOL ("modifier-keys-are-sticky", &modifier_keys_are_sticky,
  2377.     "*Non-nil makes modifier keys sticky.\n\
  2378. This means that you can release the modifier key before pressing down\n\
  2379. the key that you wish to be modified.  Although this is non-standard\n\
  2380. behavior, it is recommended because it reduces the strain on your hand,\n\
  2381. thus reducing the incidence of the dreaded Emacs-pinky syndrome.");
  2382.   modifier_keys_are_sticky = 0;
  2383.  
  2384.   DEFVAR_BOOL ("x-allow-sendevents", &x_allow_sendevents,
  2385.     "*Non-nil means to allow synthetic events.  Nil means they are ignored.\n\
  2386. Beware: allowing emacs to process SendEvents opens a big security hole.");
  2387.   x_allow_sendevents = 0;
  2388.  
  2389. #ifdef DEBUG_XEMACS
  2390.   DEFVAR_INT ("x-debug-events", &x_debug_events,
  2391.     "If non-zero, display debug information about events that XEmacs sees.\n\
  2392. Information is displayed on stderr.  Currently defined values are:\n\
  2393. \n\
  2394. 1 == non-verbose output\n\
  2395. 2 == verbose output");
  2396.   x_debug_events = 0;
  2397. #endif
  2398.  
  2399.   the_Xt_timeout_blocktype = Blocktype_new (struct Xt_timeout_blocktype);
  2400.  
  2401.   last_quit_check_signal_tick_count = 0;
  2402. }
  2403.  
  2404. void
  2405. init_event_Xt_late (void) /* called when already initialized */
  2406. {
  2407.   timeout_id_tick = 1;
  2408.   pending_timeouts = 0;
  2409.   completed_timeouts = 0;
  2410.  
  2411.   event_stream = Xt_event_stream;
  2412.   XtToolkitInitialize ();
  2413.   Xt_app_con = XtCreateApplicationContext ();
  2414.   XtAppSetFallbackResources (Xt_app_con, x_fallback_resources);
  2415.   
  2416.   /* In xselect.c */
  2417.   x_selection_timeout = (XtAppGetSelectionTimeout (Xt_app_con) / 1000);
  2418.   XSetErrorHandler (x_error_handler);
  2419.   XSetIOErrorHandler (x_IO_error_handler);
  2420.  
  2421.   FD_ZERO (&tty_device_mask);
  2422.   XtAppAddInput (Xt_app_con, signal_event_pipe[0],
  2423.          (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
  2424.          Xt_what_callback, 0);
  2425. }
  2426.